﻿package com.alstudio.utils.database;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.module.xmpp.protocol.xmpp.packact.ALMessage;
import com.alstudio.pojo.module.ButtonInfo;
import com.alstudio.pojo.module.local.LocalConfigure;
import com.alstudio.pojo.module.local.Prop;
import com.alstudio.pojo.module.local.Props;
import com.alstudio.pojo.module.local.RechargeInfo;
import com.alstudio.pojo.module.server.ServerInfo;
import com.alstudio.pojo.module.user.DateRecords;
import com.alstudio.pojo.module.user.User;
import com.alstudio.utils.account.ALAccount;
import com.alstudio.utils.formater.numeric.ALNumericUtils;
import com.alstudio.utils.log.ALLog;
import com.alstudio.utils.pinyin.PinYinUtil;

/**
 * 此类封装了关于数据库操作的方法。目前提供保存名片、修改名片、 删除全部名片、删除单条名片、获取所有未上传名片、获取所有未读名片、获取所有已读名片
 * 获取所有新收到的名片、获取所有好友更新过得名片、获取未读名片数、 获取新收到的名片数、获取好友刚刚更新过得名片数、获取所有未上传的名片数
 * 
 * 
 * @author Alonso Lee
 * 
 */
public class DatabaseUtil {

	public static final String NEW_COUNT_KEY_APPRENTICE = "apprentice";

	private final String DEFAULT_DB_NAME = "molove";
	/* 数据库名 */
	private final String DB_NAME = DEFAULT_DB_NAME + ".db";
	private final String DB_ACCOUNT = "molove_account.db";
	private final String MY_PRIVATE_ACCOUNT = "loovee_molove_my_private_account";

	// 服务器下发的系统消息
	private final String SYSTEM_MESSAGE = "loovee_molove_system_message";

	/* 我的详细约会记录 */
	private final String MY_DATE_RECORDS = "loovee_molove_my_date_record";
	// 我的约会记录
	private final String MY_DATE_HISTORY = "loovee_molove_my_date_history";
	// 我的礼物列表
	private final String MY_GIFTS_LIST = "loovee_molove_my_gifts_list";
	// 礼物分类列表
	private final String GIFT_CATEGORY_LIST = "loovee_molove_gift_category_list";
	// 当前可用礼物列表
	private final String CUR_GIFT_LIST = "loovee_molove_cur_gift_list";
	// 保存账号密码
	private final String MY_ACCOUNT = "loovee_molove_my_account";
	// 系统设置
	private final String SYSTEM_SETTING = "loovee_molove_system_setting";
	// 保存我的充值已成功但是未提交到服务器的
	private final String MY_RECHARGE_RECORD = "loovee_molove_my_recharge_record";
	// 我的约会聊天记录
	private final String MY_DATE_RECORDS_MESSAGE = "loovee_molove_my_date_record_message";
	// 我的详细留言表
	private final String MY_MESSAGE_RECORD = "loovee_molove_fac_my_message_record";
	// 登录统计
	private final String USER_LOGIN_HISTORY = "loovee_molove_user_login_history";
	// 拒绝约会邀请统计
	private final String USER_REFUSE_HISTORY = "loovee_molove_user_refuse_history";

	// 保存gps位置信息、保存上一次使用的分发器信息
	private final String LOCAL_CONFIGURE = "loovee_molover_local_configure";
	// 被收藏记录表
	private final String FAVOTITE_HISTORY = "loovee_molove_favotite_history";
	// 我的约会记录
	private final String DATING_RECORD = "loovee_molove_dating_record";
	// 道具列表
	private final String MY_PROPS_MAILL_LIST = "loovee_molove_my_props_mall_list";
	// 最近@的人
	private final String MY_PLAZA_LASTED_ADD_USER = "loovee_mylove_my_plaza_lasted_add_user";

	// new数量表
	private final String NEW_COUNT_TABLE = "loovee_mylove_new_count_table";

	private final String MY_FAVORITE_FORMY = "loovee_my_favorite_formy";// 我的收藏
	private final String MY_FAVORITE_TOMY = "loovee_my_favorite_tomy";// 我的粉丝

	private final String MY_SUBSCRIBE_TIPS = "loovee_my_subscribe_tips"; // 订阅上线提示

	private final String USER_INFO_GUIDER_TABLE = "loovee_user_info_guide"; // 4.0
																			// 新手教育订阅上线提示

	private final String USE_STATE_TABLE = "loovee_use_state_table"; // 4.0

	private final String FANS_AND_FRIENDS_COUNT = "loovee_fans_and_friends_count_table";
	private final String SELECT_REGION = "loovee_select_region_table";

	// 黑名单列表
	private final String USER_BLACK_LIST_TABLE = "loovee_user_black_list_table";

	// 通话记录
	private final String VOIP_CALL_HISTORY_TABLE = "loovee_voip_call_history_table";

	// 新手教育订阅上线提示

	private final String DATABASE_TMP_SUFIX = "_tmp";

	// 分页加载缺省20条数据
	private final int DEFAULT_PAGE_COUNT = 20;

	/* 数据库实例 */
	private SQLiteDatabase db;

	/* 数据库实例 */
	private SQLiteDatabase privateDB;

	/* 内部类，用于创建数据库 */
	private MyOpenHelper dbhelper;
	/* 内部类，用于创建数据库 */
	private AccountDBHelper privateDbhelper;

	private String curUsername;

	/* 数据库版本 */
	private final int version = 8;
	private final int privatedbVersion = 2;

	private boolean isUpdate = false;

	// 当前打开的数据库名
	private String curDatabaseName = DEFAULT_DB_NAME;

	/**
	 * DatabaseUtil类构造函数
	 * 
	 * @author Alonso Lee
	 */
	public DatabaseUtil() {

		/*
		 * if (db == null) { dbhelper = new
		 * MyOpenHelper(ALLocalEnv.getLocalEnv(), DB_NAME, version); db =
		 * dbhelper.getWritableDatabase(); }
		 */
	}

	public void loadDefaultDb() {
		closeDb();

		if (db == null) {
			dbhelper = new MyOpenHelper(ALLocalEnv.getLocalEnv(), DB_NAME,
					version);
			db = dbhelper.getWritableDatabase();
			if (curUsername != null) {
				loadDataBase(curUsername);
				curUsername = null;
			}
			curDatabaseName = DEFAULT_DB_NAME;
		}
	}

	public void closeDb() {
		if (db != null) {
			db.close();
		}

		if (dbhelper != null) {
			dbhelper.close();
		}
		dbhelper = null;
		db = null;
	}

	public DatabaseUtil(String dbName) {
		closeDb();
		if (db == null) {
			dbhelper = new MyOpenHelper(ALLocalEnv.getLocalEnv(), dbName
					+ ".db", version);
			db = dbhelper.getWritableDatabase();
			curDatabaseName = dbName;
		}
	}

	public void loadDataBase(String dbName) {
		closeDb();
		if (db == null) {
			ALLog.d("calling loadDataBase(String dbName)");
			dbhelper = new MyOpenHelper(ALLocalEnv.getLocalEnv(), dbName
					+ ".db", version);
			db = dbhelper.getWritableDatabase();
			curDatabaseName = dbName;
		}
	}

	/**
	 * 获取数据库名
	 * 
	 * @return
	 */
	public String getDatabaseName() {
		// if (dbhelper != null) {
		// String tmp = "";
		// try {
		// tmp = dbhelper.getDatabaseName();
		// } catch (Exception e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// return tmp;
		// }
		ALLog.d("獲取當前數據庫名" + curDatabaseName);
		return curDatabaseName;
	}

	/**
	 * 清空数据库所有表数据
	 * 
	 * @author Alonso Lee
	 */
	public void deletAllTable() {
		try {

			/* 我的详细约会记录 */
			db.delete(MY_DATE_RECORDS, null, null);
			// 我的约会记录
			db.delete(MY_DATE_HISTORY, null, null);
			// 服务器下发的系统消息
			db.delete(SYSTEM_MESSAGE, null, null);
			// 我的礼物列表
			db.delete(MY_GIFTS_LIST, null, null);
			// 当前可用礼物列表
			db.delete(CUR_GIFT_LIST, null, null);
			// 保存账号密码
			db.delete(MY_ACCOUNT, null, null);
			// 系统设置
			db.delete(SYSTEM_SETTING, null, null);
			// 保存我的充值已成功但是未提交到服务器的
			db.delete(MY_RECHARGE_RECORD, null, null);
			// 我的约会聊天记录
			db.delete(MY_DATE_RECORDS_MESSAGE, null, null);
			// 我的详细留言表
			db.delete(MY_MESSAGE_RECORD, null, null);
			// 登录统计
			db.delete(USER_LOGIN_HISTORY, null, null);
			// 拒绝约会邀请统计
			db.delete(USER_REFUSE_HISTORY, null, null);

			// 保存gps位置信息、保存上一次使用的分发器信息
			db.delete(LOCAL_CONFIGURE, null, null);
			// 被收藏记录表
			db.delete(FAVOTITE_HISTORY, null, null);
			// 清除最近@的人
			db.delete(MY_PLAZA_LASTED_ADD_USER, null, null);

			// 清除道具信息表
			db.delete(MY_PROPS_MAILL_LIST, null, null);

			// 清楚new数量表
			db.delete(NEW_COUNT_TABLE, null, null);
			// 清除我的收藏
			db.delete(MY_FAVORITE_FORMY, null, null);
			// 清除我的粉丝
			db.delete(MY_FAVORITE_TOMY, null, null);
			// 清除訂閱TIPS
			db.delete(MY_SUBSCRIBE_TIPS, null, null);
			db.delete(USER_INFO_GUIDER_TABLE, null, null);
			db.delete(USE_STATE_TABLE, null, null);

			db.delete(SELECT_REGION, null, null);
			db.delete(FANS_AND_FRIENDS_COUNT, null, null);
			// 删除黑名单
			db.delete(USER_BLACK_LIST_TABLE, null, null);
			deleteAllCallHitory();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void getFansAndFriendsSum(String fansCount, String friendsCount) {
		Cursor c = null;

		try {
			c = db.rawQuery("SELECT * FROM " + FANS_AND_FRIENDS_COUNT, null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			while (c.moveToNext()) {
				fansCount = (c.getString(c.getColumnIndex("_fans_count")));
				friendsCount = (c.getString(c.getColumnIndex("_friends_count")));
			}
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}
		ALLog.d("粉丝个数" + fansCount + " 好友个数 " + friendsCount);
	}

	public int getFavotiteToMyCount2() {
		Cursor c = null;
		String fansCount = null;

		try {
			c = db.rawQuery("SELECT * FROM " + FANS_AND_FRIENDS_COUNT, null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			while (c.moveToNext()) {
				fansCount = (c.getString(c.getColumnIndex("_fans_count")));
			}
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}
		ALLog.d("粉丝个数" + fansCount);
		return ALNumericUtils.parseInt(fansCount, 0);
	}

	public void insertFansAndFriendsSum(String fansCount, String friendsCount) {
		ContentValues values = new ContentValues();
		if (!TextUtils.isEmpty(fansCount)) {
			values.put("_fans_count", fansCount);
		}

		ALLog.d("我的粉丝数" + fansCount);
		if (!TextUtils.isEmpty(friendsCount)) {
			values.put("_friends_count", friendsCount);
		}

		if (db.insert(FANS_AND_FRIENDS_COUNT, "", values) == -1) {
			ALLog.d("保存总量失败");
			return;
		}
		ALLog.d("保存总量成功");
	}

	public void insertFansSum(String fansCount) {
		ContentValues values = new ContentValues();

		values.put("_fans_count", fansCount);

		if (db.insert(FANS_AND_FRIENDS_COUNT, "", values) == -1) {
			ALLog.d("保存总量失败");
			return;
		}
		ALLog.d("保存总量成功");
	}

	public String getSelectRegion() {
		String region = "";
		Cursor c = null;

		try {
			c = db.rawQuery("SELECT * FROM " + SELECT_REGION, null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			while (c.moveToNext()) {
				region = (c.getString(c.getColumnIndex("_region")));
			}
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}
		ALLog.d("选择的区域为" + region);
		return region;
	}

	public void insertSelectRegion(String region) {
		ContentValues values = new ContentValues();

		// 根据已读状态，写入数据库
		values.put("_region", region);

		if (db.insert(SELECT_REGION, "", values) == -1) {
			ALLog.d("保存选择区域失败");
			return;
		}
		ALLog.d("保存选择区域成功");
	}

	/**
	 * 检测与某个jid的约会历史记录是否存在
	 * 
	 * @param jid
	 *            需要检测的jid
	 * @return true，存在.
	 * @author Alonso Lee
	 */
	public boolean isDateHistoryExsit(String jid) {
		Cursor c = null;
		String[] arg = { jid };

		try {
			c = db.rawQuery("select * from " + MY_DATE_HISTORY
					+ " where _jid=?", arg);
		} catch (Throwable t) {
			t.printStackTrace();
		}

		if ((c != null) && (c.getCount() > 0)) {
			c.close();
			ALLog.d("jid属性为" + jid + "的约会历史存在！");
			return true;
		} else {
			if (c != null) {
				c.close();
			}
		}
		ALLog.d("jid属性为" + jid + "的约会历史不存在！");
		return false;
	}

	public void saveSystemSetting(boolean isUserLogoff) {
		ContentValues values = new ContentValues();

		// 根据已读状态，写入数据库
		if (isUserLogoff) {
			values.put("_state", 1);
		} else {
			values.put("_state", 0);
		}

		ALLog.d("系统注销标志位"+isUserLogoff);
		
		if (db.insert(SYSTEM_SETTING, "", values) == -1) {
			ALLog.d("保存系统注销标志位失败");
			return;
		}
		ALLog.d("保存系统注销标志位成功");
	}

	public boolean loadSystemSetting() {
		boolean isUserLogoff = false;

		Cursor c = null;

		try {
			c = db.rawQuery("SELECT * FROM " + SYSTEM_SETTING, null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			while (c.moveToNext()) {
				isUserLogoff = (c.getInt(c.getColumnIndex("_state")) == 1 ? true
						: false);
			}
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		return isUserLogoff;
	}

	public String loadPrivateAccount() {
		String jid = null;
		Cursor c = null;

		if (privateDB == null) {
			privateDbhelper = new AccountDBHelper(ALLocalEnv.getLocalEnv(),
					DB_ACCOUNT, privatedbVersion);
			privateDB = privateDbhelper.getWritableDatabase();
		}

		try {
			c = privateDB.rawQuery("SELECT * FROM " + MY_PRIVATE_ACCOUNT, null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			while (c.moveToNext()) {
				jid = c.getString(c.getColumnIndex("_jid"));
			}
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}
		return jid;

	}

	public void savePrivateAccount(String jid) {
		if (privateDB == null) {
			privateDbhelper = new AccountDBHelper(ALLocalEnv.getLocalEnv(),
					DB_ACCOUNT, privatedbVersion);
			privateDB = privateDbhelper.getWritableDatabase();
		}

		ContentValues values = new ContentValues();
		values.put("_jid", jid);

		if (privateDB.insert(MY_PRIVATE_ACCOUNT, "", values) == -1) {
			return;
		}
	}

	/**
	 * 将约会历史记录保存到数据库。请注意，不是保存与某人的约会详情。 只是保存约会记录的列表。
	 * 
	 * @param d
	 *            约会记录
	 * @author Alonso Lee
	 */
	public void saveDateHistory(DateRecords d) {
		// 首先检测是否已经存在历史记录
		if (isDateHistoryExsit(d.getJid())) {
			// 存在则首先删除
			deleteDateHistoryByJid(d.getJid());
		}
		ContentValues values = new ContentValues();
		values.put("_jid", d.getJid());
		values.put("_nick", d.getNick());
		values.put("_imageFileid", d.getImageFileId());
		values.put("_place", d.getDatePlace());
		values.put("_duration", d.getDuration());
		values.put("_time", d.getDateTime());
		if (d.isVip()) {
			values.put("_vip", 1);
		} else {
			values.put("_vip", 0);
		}

		if (db.insert(MY_DATE_HISTORY, "", values) == -1) {
			ALLog.d("保存约会历史失败");
			return;
		}
		ALLog.d("保存约会记录成功");
		return;
	}

	/**
	 * 按时间读取所有约会历史记录
	 * 
	 * @return 按时间排序的所有约会历史记录
	 * @author Alonso Lee
	 */
	public ArrayList<DateRecords> getDateHistoryAsTime() {
		Cursor c = null;

		try {
			c = db.rawQuery("SELECT * FROM " + MY_DATE_HISTORY
					+ " ORDER BY _time DESC", null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		ArrayList<DateRecords> list = new ArrayList<DateRecords>();

		if (c != null && c.getCount() > 0) {
			DateRecords d = null;
			while (c.moveToNext()) {
				d = new DateRecords();

				d.setJid(c.getString(c.getColumnIndex("_jid")));
				d.setDuration(c.getString(c.getColumnIndex("_duration")));
				d.setImageFileId(c.getString(c.getColumnIndex("_imageFileid")));
				d.setNick(c.getString(c.getColumnIndex("_nick")));
				d.setDateTime(c.getLong(c.getColumnIndex("_time")));
				d.setDatePlace(c.getString(c.getColumnIndex("_place")));
				d.setIsVip(c.getInt(c.getColumnIndex("_vip")) == 1 ? true
						: false);

				if (!list.contains(d)) {
					list.add(d);
				}
			}
			d = null;
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d("一共有" + list.size() + "条约会历史记录!");

		return list;
	}

	/**
	 * 删除与某人的约会历史记录。仅仅是一条！
	 * 
	 * @param jid
	 * @author Alonso Lee
	 */
	public void deleteDateHistoryByJid(String jid) {
		String[] arg = { jid };
		if (db.delete(MY_DATE_HISTORY, "(_jid=?)", arg) != -1) {
			ALLog.d("删除jid为" + jid + "的约会历史记录成功");
			return;
		}
		ALLog.d("删除jid为" + jid + "的约会历史记录失败");
	}

	/**
	 * 将约会历史记录列表清空
	 * 
	 * @author Alonso Lee
	 */
	public void deleteAllDateHistory() {
		if (db.delete(MY_DATE_HISTORY, null, null) != -1) {
			ALLog.d("删除约会历史记录列表成功");
		}
		ALLog.d("删除约会历史记录列表失败");
	}

	/**
	 * 保存约会记录
	 * 
	 * @param d
	 *            被保存的约会记录
	 * @return true 保存成功，false 保存失败
	 * @author Alonso Lee
	 */
	public boolean saveDateRecordDetail(DateRecords d) {
		ContentValues values = new ContentValues();
		values.put("_jid", d.getJid());
		values.put("_nick", d.getNick());
		values.put("_imageFileid", d.getImageFileId());
		values.put("_place", d.getDatePlace());
		values.put("_duration", d.getDuration());
		values.put("_time", d.getDateTime());
		if (d.isVip()) {
			values.put("_vip", 1);
		} else {
			values.put("_vip", 0);
		}

		if (db.insert(MY_DATE_RECORDS, "", values) == -1) {
			ALLog.d("保存约会记录失败");
			return false;
		}
		ALLog.d("保存约会记录成功");
		return true;
	}

	/**
	 * 按时间读取所有约会记录
	 * 
	 * @return 按时间排序的所有约会记录
	 * @author Alonso Lee
	 */
	public ArrayList<DateRecords> getDateRecordsAsTime() {
		Cursor c = null;

		try {
			c = db.rawQuery("SELECT * FROM " + MY_DATE_RECORDS
					+ " ORDER BY _time DESC", null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		ArrayList<DateRecords> list = new ArrayList<DateRecords>();

		if (c != null && c.getCount() > 0) {
			DateRecords d = null;
			while (c.moveToNext()) {
				d = new DateRecords();

				d.setJid(c.getString(c.getColumnIndex("_jid")));
				d.setDuration(c.getString(c.getColumnIndex("_duration")));
				d.setImageFileId(c.getString(c.getColumnIndex("_imageFileid")));
				d.setNick(c.getString(c.getColumnIndex("_nick")));
				d.setDateTime(c.getLong(c.getColumnIndex("_time")));
				d.setDatePlace(c.getString(c.getColumnIndex("_place")));
				d.setIsVip(c.getInt(c.getColumnIndex("_vip")) == 1 ? true
						: false);

				if (!list.contains(d)) {
					list.add(d);
				}
			}
			d = null;
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d("一共有" + list.size() + "条约会记录!");

		return list;
	}

	/**
	 * 获取指定与指定jid的约会记录
	 * 
	 * @param jid
	 *            待查找约会记录的jid
	 * @return 与jid的约会记录列表
	 * @author Alonso Lee
	 */
	public ArrayList<DateRecords> getDateRecordsDetailByJid(String jid) {
		Cursor c = null;
		String[] arg = { jid };

		try {
			c = db.rawQuery("SELECT * FROM " + MY_DATE_RECORDS
					+ " where _jid=? ORDER BY _time DESC", arg);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		ArrayList<DateRecords> list = new ArrayList<DateRecords>();

		if (c != null && c.getCount() > 0) {
			DateRecords d = null;
			while (c.moveToNext()) {
				d = new DateRecords();

				d.setJid(c.getString(c.getColumnIndex("_jid")));
				d.setDuration(c.getString(c.getColumnIndex("_duration")));
				d.setImageFileId(c.getString(c.getColumnIndex("_imageFileid")));
				d.setNick(c.getString(c.getColumnIndex("_nick")));
				d.setDateTime(c.getLong(c.getColumnIndex("_time")));
				d.setDatePlace(c.getString(c.getColumnIndex("_place")));
				d.setIsVip(c.getInt(c.getColumnIndex("_vip")) == 1 ? true
						: false);

				if (!list.contains(d)) {
					list.add(d);
				}
			}
			d = null;
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d("与" + jid + "一共有" + list.size() + "此约会!");

		return list;
	}

	/**
	 * 删除所有约会记录
	 * 
	 * @return true 删除成功
	 * @author Alonso Lee
	 */
	public boolean deletAllDateRecordsDetail() {
		try {
			db.delete(MY_DATE_RECORDS, null, null);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			ALLog.d("删除所有约会记录失败");
			return false;
		}
		ALLog.d("删除所有约会记录成功");
		return true;
	}

	/**
	 * 删除与JID用户的所有约会记录
	 * 
	 * @param jid
	 *            jid
	 * @return true 删除成功
	 * @author Alonso Lee
	 */
	public boolean deleteDateRecordsByJid(String jid) {
		String[] arg = { jid };
		try {
			db.delete(MY_DATE_RECORDS, "(_jid=?)", arg);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			ALLog.d("删除与jid为" + jid + "的约会记录失败");
			return false;
		}
		ALLog.d("删除与jid为" + jid + "的约会记录成功");
		return true;
	}

	/**
	 * 保存服务器下发的系统消息到数据库
	 * 
	 * @param msg
	 *            服务器下发的系统消息
	 * @author Alonso Lee
	 */
	public void saveSystemMsg(ALMessage msg) {
		ContentValues values = new ContentValues();
		values.put("_from", msg.getFrom());
		values.put("_fromNick", msg.getFromNick());
		values.put("_subject", msg.getSubject());
		values.put("_body", msg.getBody());
		values.put("_msgId", msg.getMsgId());
		values.put("_time", msg.getDate().getTime());
		values.put("_fromAvatar", msg.getFromAvatar());
		values.put("_linkBody", msg.getLinkBody());
		values.put("_org_logo", msg.getOrgLogo());

		// 根据已读状态，写入数据库
		if (msg.getDisplayed()) {
			values.put("_state", 1);
		} else {
			values.put("_state", 0);
		}

		if (msg.getButtonList() != null && msg.getButtonList().size() > 0) {

			ButtonInfo info = new ButtonInfo();

			for (int i = 0; i < msg.getButtonList().size(); i++) {
				info = msg.getButtonList().get(i);
				values.put("_button_url" + (i + 1), info.getUrl());
				values.put("_button_name" + (i + 1), info.getName());
			}
		}

		try {
			if (db.insert(SYSTEM_MESSAGE, "", values) == -1) {
				ALLog.d("保存系统消息失败");
				return;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		ALLog.d("保存系统消息成功");
	}

	public boolean isSystemMessageExsitById(String id) {
		boolean result = false;
		Cursor c = null;
		String[] args = { id };
		try {

			c = db.rawQuery("SELECT * FROM " + SYSTEM_MESSAGE
					+ " where _msgId=? ", args);

		} catch (Throwable t) {
			ALLog.d(t.toString());
		}
		if (c != null) {
			int i = c.getCount();
			if (i > 0) {
				result = true;
			}
			c.close();
		}
		return result;

	}

	/**
	 * 以时间排序读取系统消息
	 * 
	 * @return 系统消息列表
	 * @author Alonso Lee
	 */
	public ArrayList<ALMessage> getSystemMsgList(int offset) {
		Cursor c = null;

		String sql = "SELECT * FROM " + SYSTEM_MESSAGE
				+ "  ORDER BY _time DESC LIMIT " + DEFAULT_PAGE_COUNT
				+ " offset " + offset;

		try {
			// c = db.rawQuery("SELECT * FROM " + SYSTEM_MESSAGE
			// + " ORDER BY _time DESC", null);

			c = db.rawQuery(sql, null);

		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		ArrayList<ALMessage> list = new ArrayList<ALMessage>();
		ArrayList<ButtonInfo> buttonList = new ArrayList<ButtonInfo>();
		ButtonInfo info = null;

		if (c != null && c.getCount() > 0) {
			ALMessage msg = null;
			while (c.moveToNext()) {
				msg = new ALMessage();

				msg.setFrom(c.getString(c.getColumnIndex("_from")));
				msg.setFromNick(c.getString(c.getColumnIndex("_fromNick")));
				msg.setSubject(c.getString(c.getColumnIndex("_subject")));
				msg.setBody(c.getString(c.getColumnIndex("_body")));
				msg.setDate(new Date(c.getLong(c.getColumnIndex("_time"))));
				msg.setMsgId(c.getString(c.getColumnIndex("_msgId")));
				msg.setDisplayed(c.getInt(c.getColumnIndex("_state")) == 1 ? true
						: false);
				msg.setFromAvatar(c.getString(c.getColumnIndex("_fromAvatar")));
				msg.setLinkBody(c.getString(c.getColumnIndex("_linkBody")));
				msg.setOrgLogo(c.getString(c.getColumnIndex("_org_logo")));

				buttonList = new ArrayList<ButtonInfo>();
				String buttonName = c.getString(c
						.getColumnIndex("_button_name1"));
				String buttonUrl = c
						.getString(c.getColumnIndex("_button_url1"));

				if (!TextUtils.isEmpty(buttonName)
						&& !TextUtils.isEmpty(buttonUrl)) {
					info = new ButtonInfo();
					info.setName(buttonName);
					info.setUrl(buttonUrl);
					buttonList.add(info);
				}
				buttonName = c.getString(c.getColumnIndex("_button_name2"));
				buttonUrl = c.getString(c.getColumnIndex("_button_url2"));

				if (!TextUtils.isEmpty(buttonName)
						&& !TextUtils.isEmpty(buttonUrl)) {
					info = new ButtonInfo();
					info.setName(buttonName);
					info.setUrl(buttonUrl);
					buttonList.add(info);
				}

				msg.setButtonList(buttonList);

				if (!list.contains(msg)) {
					list.add(msg);
				}
			}
			msg = null;
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d("分页一共有" + list.size() + "条系统消息!");

		return list;
	}

	/**
	 * 以时间排序读取系统消息
	 * 
	 * @return 系统消息列表
	 * @author Alonso Lee
	 */
	public ArrayList<ALMessage> getSystemMsgList() {
		Cursor c = null;
		try {
			c = db.rawQuery("SELECT * FROM " + SYSTEM_MESSAGE
					+ " ORDER BY _time DESC", null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		ArrayList<ALMessage> list = new ArrayList<ALMessage>();
		ArrayList<ButtonInfo> buttonList = new ArrayList<ButtonInfo>();
		ButtonInfo info = null;

		if (c != null && c.getCount() > 0) {
			ALMessage msg = null;
			while (c.moveToNext()) {
				msg = new ALMessage();

				msg.setFrom(c.getString(c.getColumnIndex("_from")));
				msg.setFromNick(c.getString(c.getColumnIndex("_fromNick")));
				msg.setSubject(c.getString(c.getColumnIndex("_subject")));
				msg.setBody(c.getString(c.getColumnIndex("_body")));
				msg.setDate(new Date(c.getLong(c.getColumnIndex("_time"))));
				msg.setMsgId(c.getString(c.getColumnIndex("_msgId")));
				msg.setDisplayed(c.getInt(c.getColumnIndex("_state")) == 1 ? true
						: false);
				msg.setFromAvatar(c.getString(c.getColumnIndex("_fromAvatar")));
				msg.setLinkBody(c.getString(c.getColumnIndex("_linkBody")));
				msg.setOrgLogo(c.getString(c.getColumnIndex("_org_logo")));

				// String type = c.getString(c.getColumnIndex("_type"));
				// if (type != null) {
				// if (type.equals("gift")) {
				// msg.setGifts(new Gifts());
				// } else if (type.equals("praise")) {
				// msg.setPraise(new Praise());
				// }
				// }

				buttonList = new ArrayList<ButtonInfo>();
				String buttonName = c.getString(c
						.getColumnIndex("_button_name1"));
				String buttonUrl = c
						.getString(c.getColumnIndex("_button_url1"));

				if (!TextUtils.isEmpty(buttonName)
						&& !TextUtils.isEmpty(buttonUrl)) {
					info = new ButtonInfo();
					info.setName(buttonName);
					info.setUrl(buttonUrl);
					buttonList.add(info);
				}
				buttonName = c.getString(c.getColumnIndex("_button_name2"));
				buttonUrl = c.getString(c.getColumnIndex("_button_url2"));

				if (!TextUtils.isEmpty(buttonName)
						&& !TextUtils.isEmpty(buttonUrl)) {
					info = new ButtonInfo();
					info.setName(buttonName);
					info.setUrl(buttonUrl);
					buttonList.add(info);
				}

				msg.setButtonList(buttonList);

				if (!list.contains(msg)) {
					list.add(msg);
				}
			}
			msg = null;
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d("一共有" + list.size() + "条系统消息!");

		return list;
	}

	/**
	 * 以时间排序读取系统消息
	 * 
	 * @return 系统消息列表
	 * @author Alonso Lee
	 */
	public int getSystemMsgCount() {
		Cursor c = null;
		int count = 0;
		try {
			c = db.rawQuery("SELECT * FROM " + SYSTEM_MESSAGE
					+ " ORDER BY _time DESC", null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			count = c.getCount();
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d("一共有" + count + "条系统消息!");

		return count;
	}

	/**
	 * 获取未读系统消息数
	 * 
	 * @return 未读系统消息数
	 * @author Alonso Lee
	 */
	public int getCountOfUnreadSystemMsg() {
		int i = 0;
		Cursor c = null;
		try {
			c = db.rawQuery("SELECT count(*) as counts FROM " + SYSTEM_MESSAGE
					+ " where _state=0", null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {

			if (c.moveToNext()) {
				i = c.getInt(c.getColumnIndex("counts"));
			}
		}

		if (c != null) {
			c.close();
		}
		return i;
	}

	/**
	 * 将指定id的系统消息设为已读
	 * 
	 * @param id
	 *            要设为已读的系统消息id
	 * @author Alonso Lee
	 */
	public void setSystemMessageReaded(final String id) {
		String[] arg = { id };
		ContentValues values = new ContentValues();
		values.put("_state", 1);
		db.update(SYSTEM_MESSAGE, values, "_msgId=?", arg);
	}

	/**
	 * 删除指定msgid的系统消息
	 * 
	 * @param msgId
	 * @author Alonso Lee
	 */
	public void deleteSystemMsgById(String msgId) {
		String[] arg = { msgId };
		db.delete(SYSTEM_MESSAGE, "(_msgId=?)", arg);
	}

	/**
	 * 删除所有系统消息
	 * 
	 * @author Alonso Lee
	 */
	public void deleteAllSystemMsg() {
		db.delete(SYSTEM_MESSAGE, null, null);
		ALLog.d("删除所有系统消息完成！");
	}

	/**
	 * 保存我的账号信息
	 * 
	 * @param account
	 *            我的账号信息
	 * @author Alonso Lee
	 */
	public void saveMyAccount(ALAccount account) {
		if (account == null) {
			ALLog.d("你妹的！传个空的对象给我，存个毛线啊！");
			return;
		}
		ContentValues values = new ContentValues();
		values.put("_username", account.getUserName());
		values.put("_password", account.getPassWord());
		values.put("_customName", account.getCustomName());
		values.put("_loginType", account.getLoginType());

		ALLog.d("保存我的账号" + account.getUserName() + "\n密码"
				+ account.getPassWord() + "\n登录类型" + account.getLoginType());

		if (db.insert(MY_ACCOUNT, "", values) == -1) {
			ALLog.d("保存我的账号信息失败");
			return;
		}
		ALLog.d("保存我的账号成功");
	}

	/**
	 * 读取我的账号信息
	 * 
	 * @return 我的账号信息
	 * @author Alonso Lee
	 */
	public ALAccount loadMyAccount() {
		ALAccount account = new ALAccount();

		Cursor c = null;

		try {
			c = db.rawQuery("SELECT * FROM " + MY_ACCOUNT, null);
		} catch (Throwable t) {
			ALLog.d("loadMyAccount" + t.toString());
		}

		if (c != null && c.getCount() > 0) {
			while (c.moveToNext()) {
				account.setUserName(c.getString(c.getColumnIndex("_username")));
				account.setPassWord(c.getString(c.getColumnIndex("_password")));
				account.setCustomName(c.getString(c
						.getColumnIndex("_customName")));
				account.setLoginType(c.getInt(c.getColumnIndex("_loginType")));
			}
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		if (account.getUserName() != null) {
			if (account.getUserName().equals("")) {
				// account.setUserName(null);
			}
		}

		ALLog.d("用户名:" + account.getUserName() + "\n密码:"
				+ account.getPassWord() + "\n登录类型" + account.getLoginType());

		return account;
	}

	/**
	 * 保存未上传的充值信息到数据库，下次登录再上传
	 * 
	 * @param info
	 *            充值信息
	 * @author Alonso Lee
	 */
	public void saveRechargeRecord(RechargeInfo info) {
		if (info == null) {
			ALLog.d("你妹的！传个空的对象给我，存个毛线啊！");
			return;
		}
		ContentValues values = new ContentValues();
		values.put("_type", info.getType());
		values.put("_orderid", info.getOrderNumber());
		values.put("_productid", info.getProductId());

		ALLog.d("保存充值信息,类型:" + info.getType() + ",单号:" + info.getOrderNumber()
				+ "\nid号:" + info.getProductId());

		if (db.insert(MY_RECHARGE_RECORD, "", values) == -1) {
			ALLog.d("保存充值信息失败");
			return;
		}
		ALLog.d("保存充值信息成功");

	}

	/**
	 * 读取所有未上传的充值信息
	 * 
	 * @return
	 * @author Alonso Lee
	 */
	public ArrayList<RechargeInfo> loadRechargeRecords() {
		ArrayList<RechargeInfo> list = new ArrayList<RechargeInfo>();
		RechargeInfo info = null;

		Cursor c = null;

		try {
			c = db.rawQuery("SELECT * FROM " + MY_RECHARGE_RECORD, null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			while (c.moveToNext()) {
				info = new RechargeInfo();
				info.setType(c.getInt(c.getColumnIndex("_type")));
				info.setOrderNumber(c.getString(c.getColumnIndex("_orderid")));
				info.setProductId(c.getString(c.getColumnIndex("_productid")));
				if (!list.contains(info)) {
					list.add(info);
				}
			}
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d("未上传充值订单有" + list.size());

		return list;
	}

	/**
	 * 删除所有未上传的充值信息
	 * 
	 * @author Alonso Lee
	 */
	public void deletAllRechargeRecords() {
		try {
			db.delete(MY_RECHARGE_RECORD, null, null);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 删除指定单号的充值信息
	 * 
	 * @param orderid
	 *            单号
	 * @author Alonso Lee
	 */
	public void deletRechargeRecordByOrderId(String orderid) {
		String[] arg = { orderid };

		if (db.delete(MY_RECHARGE_RECORD, "(_orderid=?)", arg) != -1) {
			ALLog.d("删除orderid为" + orderid + "的充值记录成功");
			return;
		}
		ALLog.d("删除orderid为" + orderid + "的充值记录失败");
	}

	// 保存约会聊天记录
	public void saveDateRecordMessage(ALMessage rm) {

		if (rm == null) {
			ALLog.d("传入的约会聊天对象的为null");
			return;
		}

		if (TextUtils.isEmpty(rm.getJid())) {
			ALLog.d("传入的约会聊天对象的为null");
			return;
		}

		deleteDateRecordMessageByMsgId(rm.getMsgId());

		ContentValues cv = new ContentValues();
		cv.put("_jid", rm.getJid());
		cv.put("_time", rm.getDate().getTime());
		cv.put("_type", rm.getType());
		cv.put("_from", rm.getFrom());
		cv.put("_to", rm.getTo());
		cv.put("_body", rm.getBody());
		cv.put("_fromNick", rm.getFromNick());
		cv.put("_toNick", rm.getToNick());
		cv.put("_subject", rm.getSubject());
		cv.put("_msgId", rm.getMsgId());
		cv.put("_fileId", rm.getFIleId());
		cv.put("_reclen", rm.getRecLen());
		cv.put("_path", rm.getFilePath());
		// if (rm.getChatFace() != null) {
		// cv.put("_faceId", rm.getChatFace().getFileid());
		// cv.put("_faceName", rm.getChatFace().getName());
		// }

		// 根据已读状态，写入数据库
		if (rm.getDisplayed()) {
			cv.put("_state", 1);
		} else {
			cv.put("_state", 0);
		}

		if (rm.getType() == ALMessage.IMAGE_MSG
				|| rm.getType() == ALMessage.AUDIO_MSG && rm.getFrom() != null
				&& rm.isMyMessage()) {
			cv.put("_state", rm.getMsgState());
		}

		switch (rm.getMsgState()) {
		case ALMessage.STATE_FAILED:
			cv.put("_deliverStste", 0);
			break;
		default:
			cv.put("_deliverStste", 1);
			break;
		}

		// if(rm.isFromHelper()){
		// cv.put("_isFromWaiter", 1);
		// }else{
		// cv.put("_isFromWaiter", 0);
		// }

		if (db.insert(MY_DATE_RECORDS_MESSAGE, null, cv) != -1) {

		} else {

			ALLog.d("保存约会消息记录失败 msgId为:" + rm.getMsgId());
		}
	}

	/**
	 * 根据jid 获取约会聊天记录的数量
	 * 
	 * @param jid
	 * @return
	 */
	public int getRecordMessageCountByJid(String jid) {
		int count = 0;

		Cursor c = null;
		String arg[] = { jid };

		String sql = "SELECT * FROM " + MY_DATE_RECORDS_MESSAGE
				+ " WHERE _jid = ?";

		try {
			c = db.rawQuery(sql, arg);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		if (null != c) {
			count = c.getCount();
			c.close();
		}

		return count;
	}

	/**
	 * 根据msgId 获取约会聊天记录
	 * 
	 * @param msgId
	 * @return
	 */
	public ALMessage getRecordMessageByMsgId(String msgId) {

		Cursor c = null;
		ALMessage rd = null;
		String arg[] = { msgId };

		String sql = "SELECT * FROM " + MY_DATE_RECORDS_MESSAGE
				+ " WHERE _msgId = ? ";

		try {
			c = db.rawQuery(sql, arg);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		if (c.moveToNext()) {
			rd = new ALMessage();
			rd.setJid(c.getString(c.getColumnIndex("_jid")));
			rd.setMsgId(c.getString(c.getColumnIndex("_msgId")));
			Date date = new Date(c.getLong(c.getColumnIndex("_time")));
			rd.setDate(date);
			rd.setType(c.getInt(c.getColumnIndex("_type")));
			rd.setFrom(c.getString(c.getColumnIndex("_from")));
			rd.setTo(c.getString(c.getColumnIndex("_to")));
			rd.setBody(c.getString(c.getColumnIndex("_body")));
			rd.setFromNick(c.getString(c.getColumnIndex("_fromNick")));
			rd.setToNick(c.getString(c.getColumnIndex("_toNick")));
			rd.setSubject(c.getString(c.getColumnIndex("_subject")));
			rd.setFileId(c.getString(c.getColumnIndex("_fileId")));

			rd.setFilePath(c.getString(c.getColumnIndex("_path")));
			rd.setRecLen(c.getString(c.getColumnIndex("_reclen")));
			// rd.setChatFace(new ChatFace(
			// c.getString(c.getColumnIndex("_faceId")), c.getString(c
			// .getColumnIndex("_faceName"))));
			rd.setDisplayed(c.getInt(c.getColumnIndex("_state")) == 1 ? true
					: false);
			// // 发送状态
			// rd.setMsgState(c.getInt(c.getColumnIndex("_deliverStste")));

			// 发送状态,暂时服用state
			rd.setMsgState(c.getInt(c.getColumnIndex("_state")));

			// rd.setFromHelper(c.getInt(c.getColumnIndex("_isFromWaiter")) == 1
			// ? true : false);
		}

		if (null != c) {

			try {
				c.close();
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		return rd;
	}

	/**
	 * 根据对方jid 获取约会聊天记录
	 * 
	 * @param jid
	 * @return
	 */
	public int getRecordMessageListByJid(String jid) {
		int count = 0;
		Cursor c = null;

		if (TextUtils.isEmpty(jid)) {
			ALLog.d("getRecordMessageListByJid 尼玛 jid是空的...");
			return count;
		}

		String sql = "select count(*) as counts from  "
				+ MY_DATE_RECORDS_MESSAGE + " where _jid = ?";
		String arg[] = { jid };

		try {
			c = db.rawQuery(sql, arg);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (c != null && c.getCount() > 0) {

			while (c.moveToNext()) {
				count = c.getInt(c.getColumnIndex("counts"));
			}
		}

		if (c != null) {
			c.close();
		}

		ALLog.d(jid + " 聊天记录的个数 count:" + count);
		return count;
	}

	/**
	 * 根据对方jid 获取约会聊天记录
	 * 
	 * @param jid
	 * @param offset
	 *            限制
	 * @return
	 */
	public ArrayList<ALMessage> getRecordMessageListByJid(String jid, int offset) {

		ArrayList<ALMessage> list = new ArrayList<ALMessage>();
		Cursor c = null;
		ALMessage rd = null;
		String arg[] = { jid };

		String sql = "SELECT * FROM " + MY_DATE_RECORDS_MESSAGE
				+ " WHERE _jid = ?  ORDER BY _time DESC LIMIT " + (offset + 1)
				* DEFAULT_PAGE_COUNT;
		;

		try {
			c = db.rawQuery(sql, arg);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (null != c && c.getCount() > 0) {

			while (c.moveToNext()) {
				rd = new ALMessage();
				rd.setJid(c.getString(c.getColumnIndex("_jid")));
				rd.setMsgId(c.getString(c.getColumnIndex("_msgId")));
				Date date = new Date(c.getLong(c.getColumnIndex("_time")));
				rd.setDate(date);
				rd.setType(c.getInt(c.getColumnIndex("_type")));
				rd.setFrom(c.getString(c.getColumnIndex("_from")));
				rd.setTo(c.getString(c.getColumnIndex("_to")));
				rd.setBody(c.getString(c.getColumnIndex("_body")));
				rd.setFromNick(c.getString(c.getColumnIndex("_fromNick")));
				rd.setToNick(c.getString(c.getColumnIndex("_toNick")));
				rd.setSubject(c.getString(c.getColumnIndex("_subject")));
				rd.setFileId(c.getString(c.getColumnIndex("_fileId")));

				rd.setFilePath(c.getString(c.getColumnIndex("_path")));
				rd.setRecLen(c.getString(c.getColumnIndex("_reclen")));
				// rd.setChatFace(new ChatFace(c.getString(c
				// .getColumnIndex("_faceId")), c.getString(c
				// .getColumnIndex("_faceName"))));

				rd.setDisplayed(c.getInt(c.getColumnIndex("_state")) == 1 ? true
						: false);

				// rd.setFromHelper(c.getInt(c.getColumnIndex("_isFromWaiter"))
				// == 1 ? true : false);

				// 发送状态
				rd.setMsgState(c.getInt(c.getColumnIndex("_deliverStste")));
				// 发送状态,暂时服用state
				rd.setMsgState(c.getInt(c.getColumnIndex("_state")));
				if (!list.contains(rd)) {

					list.add(rd);
				}

			}

			rd = null;
		}

		if (null != c) {

			try {
				c.close();
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		return list;
	}

	/**
	 * 根据对方jid 获取所有约会聊天记录
	 * 
	 * @param jid
	 * @param direction
	 *            true 正向 false 反向
	 * @return
	 */
	public ArrayList<ALMessage> getAllRecordMessageListByJid(String jid,
			boolean direction, int offset) {

		ArrayList<ALMessage> list = new ArrayList<ALMessage>();
		// Cursor c = null;
		// ALMessage rd = null;
		// String arg[] = { jid, ALMessage.GIFT_TIMER_MSG_NOSHOW + "" };
		//
		// String sql = "SELECT * FROM " + MY_DATE_RECORDS_MESSAGE
		// + " WHERE _jid = ? AND _type!=? ORDER BY _time ";
		// if (!direction) {
		// sql += "DESC";
		// } else {
		// sql += "";
		// }
		// sql += " LIMIT " + (offset + 1) * DEFAULT_PAGE_COUNT;
		// try {
		// c = db.rawQuery(sql, arg);
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		//
		// if (null != c && c.getCount() > 0) {
		//
		// while (c.moveToNext()) {
		// rd = new ALMessage();
		// rd.setJid(c.getString(c.getColumnIndex("_jid")));
		// rd.setMsgId(c.getString(c.getColumnIndex("_msgId")));
		// Date date = new Date(c.getLong(c.getColumnIndex("_time")));
		// rd.setDate(date);
		// rd.setType(c.getInt(c.getColumnIndex("_type")));
		// rd.setFrom(c.getString(c.getColumnIndex("_from")));
		// rd.setTo(c.getString(c.getColumnIndex("_to")));
		// rd.setBody(c.getString(c.getColumnIndex("_body")));
		// rd.setFromNick(c.getString(c.getColumnIndex("_fromNick")));
		// rd.setToNick(c.getString(c.getColumnIndex("_toNick")));
		// rd.setSubject(c.getString(c.getColumnIndex("_subject")));
		// rd.setFileId(c.getString(c.getColumnIndex("_fileId")));
		//
		// rd.setFilePath(c.getString(c.getColumnIndex("_path")));
		// rd.setRecLen(c.getString(c.getColumnIndex("_reclen")));
		// rd.setChatFace(new ChatFace(c.getString(c
		// .getColumnIndex("_faceId")), c.getString(c
		// .getColumnIndex("_faceName"))));
		// rd.setDisplayed(c.getInt(c.getColumnIndex("_state")) == 1 ? true
		// : false);
		//
		// rd.setFromHelper(c.getInt(c.getColumnIndex("_isFromWaiter")) == 1 ?
		// true : false);
		//
		// // 发送状态
		// rd.setMsgState(c.getInt(c.getColumnIndex("_deliverStste")));
		// // 发送状态,暂时服用state
		// rd.setMsgState(c.getInt(c.getColumnIndex("_state")));
		// if (rd.getType() == ALMessage.FLOWERBALLHITMSG) {
		// // 抛绣球的消息
		// Ball ball = getDatingBallForMyBallHistory(rd.getMsgId());
		// if (ball != null) {
		// ALLog.d( "有喔");
		// rd.setBall(ball);
		// }
		// continue;
		// }
		//
		// if (!list.contains(rd)) {
		//
		// list.add(rd);
		// }
		//
		// }
		//
		// rd = null;
		// }
		//
		// if (null != c) {
		//
		// try {
		// c.close();
		// } catch (Exception e) {
		// // TODO: handle exception
		// e.printStackTrace();
		// }
		// }
		return list;
	}

	public ALMessage loadMessageByFileId(String fileid) {
		ALMessage msg = new ALMessage();

		// String arg[] = { fileid };
		//
		// Cursor c = null;
		//
		// try {
		// c = db.rawQuery("SELECT * FROM " + MY_DATE_RECORDS_MESSAGE
		// + " WHERE _fileId = ? ", arg);
		// } catch (Throwable t) {
		// ALLog.d( t.toString());
		// }
		//
		// if (c != null && c.getCount() > 0) {
		// while (c.moveToNext()) {
		//
		// msg.setJid(c.getString(c.getColumnIndex("_jid")));
		// msg.setMsgId(c.getString(c.getColumnIndex("_msgId")));
		// Date date = new Date(c.getLong(c.getColumnIndex("_time")));
		// msg.setDate(date);
		// msg.setType(c.getInt(c.getColumnIndex("_type")));
		// msg.setFrom(c.getString(c.getColumnIndex("_from")));
		// msg.setTo(c.getString(c.getColumnIndex("_to")));
		// msg.setBody(c.getString(c.getColumnIndex("_body")));
		// msg.setFromNick(c.getString(c.getColumnIndex("_fromNick")));
		// msg.setToNick(c.getString(c.getColumnIndex("_toNick")));
		// msg.setSubject(c.getString(c.getColumnIndex("_subject")));
		// msg.setFileId(c.getString(c.getColumnIndex("_fileId")));
		// msg.setFilePath(c.getString(c.getColumnIndex("_path")));
		// msg.setRecLen(c.getString(c.getColumnIndex("_reclen")));
		// msg.setChatFace(new ChatFace(c.getString(c
		// .getColumnIndex("_faceId")), c.getString(c
		// .getColumnIndex("_faceName"))));
		//
		// // 发送状态
		// msg.setMsgState(c.getInt(c.getColumnIndex("_deliverStste")));
		// msg.setMsgState(c.getInt(c.getColumnIndex("_state")));
		//
		// msg.setDisplayed(c.getInt(c.getColumnIndex("_state")) == 1 ? true
		// : false);
		//
		// msg.setFromHelper(c.getInt(c.getColumnIndex("_isFromWaiter")) == 1 ?
		// true : false);
		//
		// }
		// }
		// if (c != null) {
		// try {
		// c.close();
		// } catch (Exception e) {
		// }
		// }

		return msg;

	}

	/**
	 * 根据msgId删除约会聊天记录
	 * 
	 * @param msgId
	 */
	public void deleteDateRecordMessageByMsgId(String msgId) {

		String arg[] = { msgId };
		if (db.delete(MY_DATE_RECORDS_MESSAGE, "(_msgId=?)", arg) != -1) {

			ALLog.d("删除MsgId为" + msgId + "的约会消息记录成功");
		} else {
			ALLog.d("删除MsgId为" + msgId + "的约会消息记录失败");
		}
	}

	/**
	 * 获取所有未读的消息数
	 * 
	 * @return
	 */
	public int getUnreadMessageCountByJid(String jid) {

		int i = 0;
		Cursor c = null;
		String[] args = { jid };
		try {

			c = db.rawQuery("SELECT count(*) as counts FROM "
					+ MY_DATE_RECORDS_MESSAGE + " where _state=0 and _jid=?",
					args);

		} catch (Throwable t) {
			ALLog.d(t.toString());
		}
		if (c != null) {
			if (c.moveToNext()) {
				i = c.getInt(c.getColumnIndex("counts"));
			}
			c.close();
		}
		return i;
	}

	/**
	 * 获取所有已读的消息数
	 * 
	 * @return
	 */
	public int getAlreadyReadMessageCountByJid(String jid) {

		int i = 0;
		Cursor c = null;
		String[] args = { jid };
		try {

			c = db.rawQuery("SELECT count(*) as counts FROM "
					+ MY_DATE_RECORDS_MESSAGE + " where _state=1 and _jid=?",
					args);

		} catch (Throwable t) {
			ALLog.d(t.toString());
		}
		if (c != null) {
			if (c.moveToNext()) {
				i = c.getInt(c.getColumnIndex("counts"));
			}
			c.close();
		}
		return i;
	}

	/**
	 * 获取未读消息的所有jid列表
	 * 
	 * @return
	 */
	public ArrayList<String> getUnreadMessageJidList() {
		ArrayList<String> list = new ArrayList<String>();
		String jid = null;
		Cursor c = null;
		try {
			c = db.rawQuery("SELECT * FROM " + MY_DATE_RECORDS_MESSAGE
					+ " where _state=0 ORDER BY _time DESC", null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			while (c.moveToNext()) {

				jid = c.getString(c.getColumnIndex("_jid"));
				if (!list.contains(jid)) {
					ALLog.d("未读消息的jid" + jid);
					list.add(jid);
				}

			}
		}

		if (c != null) {
			c.close();
		}
		return list;
	}

	/**
	 * 将指定id的消息设为已读
	 * 
	 * @param id
	 *            要设为已读的消息id
	 * @author Alonso Lee
	 */
	public void setMessageReadedByMsgId(final String id) {
		String[] arg = { id };
		ContentValues values = new ContentValues();
		values.put("_state", 1);
		db.update(MY_DATE_RECORDS_MESSAGE, values, "_msgId=?", arg);
	}

	/**
	 * 将指定id的消息设为已读
	 * 
	 * @param id
	 *            要设为已读的消息id
	 * @author Alonso Lee
	 */
	public void setMessageSendStateByMsgId(final String id, final int state) {
		String[] arg = { id };
		ContentValues values = new ContentValues();
		values.put("_deliverStste", state);
		values.put("_state", state);
		db.update(MY_DATE_RECORDS_MESSAGE, values, "_msgId=?", arg);
	}

	/**
	 * 设定指定jid的所有消息为已读
	 * 
	 * @param jid
	 */
	public void setAllMessageReadedByJid(String jid) {
		String[] arg = { jid };
		ContentValues values = new ContentValues();
		values.put("_state", 1);
		db.update(MY_DATE_RECORDS_MESSAGE, values, "_jid=? ", arg);
	}

	public void deleteAllMessageByJids(ArrayList<String> jids) {
		if (jids == null || jids.size() == 0) {
			return;
		}
		for (String jid : jids) {
			deleteAllMessageByJid(jid);
		}
	}

	public void deleteAllMessageByJid(String jid) {
		if (TextUtils.isEmpty(jid)) {
			return;
		}

		String[] arg = { jid };

		if (db.delete(MY_DATE_RECORDS_MESSAGE, "(_jid=?)", arg) != -1) {
			ALLog.d("删除与jid为" + jid + "的聊天记录成功");
		} else {
			ALLog.d("删除与jid为" + jid + "的聊天记录失败");
		}
	}

	/**
	 * 设定指定jid的所有非图片和非音频消息为已读
	 * 
	 * @param jid
	 */
	public int setAllMessageReadedByJidForImageAndAudio(String jid) {
		// String[] arg = { jid,ALMessage.IMAGE_MSG+"",ALMessage.AUDIO_MSG+"" };
		String[] arg = { jid };
		ContentValues values = new ContentValues();
		values.put("_state", 1);
		// db.update(MY_DATE_RECORDS_MESSAGE, values,
		// "_jid=? and _type not in (?,?)", arg);
		db.update(MY_DATE_RECORDS_MESSAGE, values, "_jid=? and _state=0", arg);
		return getUnreadMessageCountByJid(jid);
	}

	/**
	 * 删除所有留言记录
	 */
	public void deleteAllMessageRecord() {
		db.delete(MY_MESSAGE_RECORD, null, null);
	}

	/**
	 * 根据类型删除所有留言记录
	 */
	public void deleteAllMessageRecord(int type) {
		db.delete(MY_MESSAGE_RECORD, "_type=" + type, null);
	}

	/**
	 * 根据类型删除所有留言记录
	 */
	public void deleteAllMessageRecord(String type) {
		String[] arg = { type };
		db.delete(MY_MESSAGE_RECORD, "_type=?", arg);
	}

	/**
	 * 
	 * @Title: updateSystemMessageByType
	 * @Description: 根据类型修改系统通知状态
	 * @param @param type 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	public void updateSystemMessageByType() {
		ContentValues values = new ContentValues();
		values.put("_state", 1);
		db.update(SYSTEM_MESSAGE, values, "_state=0", null);
	}

	/**
	 * 
	 * @Title: updateMessageByType
	 * @Description: 根据类型修改留言通知状态
	 * @param @param type 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	public void updateMessageByType(int type) {
		ContentValues values = new ContentValues();
		values.put("_state", 1);
		db.update(MY_MESSAGE_RECORD, values, "_state=0 and _type=" + type, null);
	}

	/**
	 * 
	 * @Title: updateMessageByType
	 * @Description: 根据类型修改留言通知状态
	 * @param @param type 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	public void updateMessageByType(String type) {
		String[] arg = { type };
		ContentValues values = new ContentValues();
		values.put("_state", 1);
		db.update(MY_MESSAGE_RECORD, values, "_state=0 and _type=?", arg);
	}

	/**
	 * 删除与某个jid用户的留言记录
	 * 
	 * @param jid
	 */
	public void deletMessageRecordByJid(String jid) {
		String[] arg = { jid };
		db.delete(MY_MESSAGE_RECORD, "(_jid=?)", arg);
	}

	/**
	 * 删除与某条留言记录
	 * 
	 * @param msgid
	 */
	public void deletMessageRecordByMsgId(String msgid) {
		String[] arg = { msgid };
		db.delete(MY_MESSAGE_RECORD, "(_msgId=?)", arg);
	}

	/**
	 * 获取与制定jid用户间未读的留言条目数
	 * 
	 * @param jid
	 * @return
	 */
	public int loadNumberOfUnreadMessageRecordByJid(String jid) {
		int i = 0;
		String[] arg = { jid };
		Cursor c = null;
		try {
			c = db.rawQuery("SELECT * FROM " + MY_MESSAGE_RECORD
					+ " where _state=0 and _jid=?", arg);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}
		if (c != null) {
			i = c.getCount();
			c.close();
		}
		return i;
	}

	/**
	 * 读取所有未读的留言条目总数
	 * 
	 * @return
	 */
	public int loadAllNumberOfUnreadMessageRecord() {
		int i = 0;
		Cursor c = null;
		try {
			c = db.rawQuery("SELECT count(*)  as counts  FROM "
					+ MY_MESSAGE_RECORD + " where _state=0", null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}
		if (c != null && c.getCount() > 0) {

			if (c.moveToNext()) {
				i = c.getInt(c.getColumnIndex("counts"));
			}
		}

		if (c != null) {
			c.close();
		}
		return i;
	}

	/**
	 * 根据类型读取未读消息
	 * 
	 * @return
	 */
	public int loadAllNumberOfUnreadMessageRecord(String type) {
		int i = 0;
		Cursor c = null;

		String[] arg = { type };

		try {
			c = db.rawQuery("SELECT count(*)  as counts  FROM "
					+ MY_MESSAGE_RECORD + " where _state=0 and _type=?", arg);
		} catch (Throwable t) {
			// ALLog.d( t.toString());
			t.printStackTrace();
		}
		if (c != null && c.getCount() > 0) {

			if (c.moveToNext()) {
				i = c.getInt(c.getColumnIndex("counts"));
			}
		}

		if (c != null) {
			c.close();
		}
		return i;
	}

	/**
	 * 读取与某jid的所有留言
	 * 
	 * @param jid
	 * @return
	 */
	public ArrayList<ALMessage> loadMessageRecordByJid(String jid) {
		ArrayList<ALMessage> list = null;

		ArrayList<ButtonInfo> buttonList = null;

		ButtonInfo info = null;
		String[] args = { jid };
		Cursor c = null;
		try {
			c = db.rawQuery("SELECT * FROM " + MY_MESSAGE_RECORD
					+ " where _jid=? ORDER BY _time DESC", args);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			ALMessage msg = null;
			while (c.moveToNext()) {
				msg = new ALMessage();

				msg.setFrom(c.getString(c.getColumnIndex("_from")));
				msg.setTo(c.getString(c.getColumnIndex("_to")));
				msg.setFromNick(c.getString(c.getColumnIndex("_fromNick")));
				msg.setToNick(c.getString(c.getColumnIndex("_toNick")));
				msg.setSubject(c.getString(c.getColumnIndex("_subject")));
				msg.setBody(c.getString(c.getColumnIndex("_body")));
				msg.setLinkBody(c.getString(c.getColumnIndex("_body2")));
				msg.setLinkBody2(c.getString(c.getColumnIndex("_body3")));
				msg.setTime(new Date(c.getLong(c.getColumnIndex("_time"))));
				// msg.setDate(new Date(c.getLong(c.getColumnIndex("_time"))));
				msg.setMsgId(c.getString(c.getColumnIndex("_msgId")));
				msg.setJid(c.getString(c.getColumnIndex("_jid")));
				msg.setDisplayed(c.getInt(c.getColumnIndex("_state")) == 1 ? true
						: false);
				// 语音留言
				msg.setAudioFaceId(c.getString(c.getColumnIndex("_audiofileid")));
				
				//性别
				msg.setSex(c.getString(c.getColumnIndex("_sex")));
				//V认证
				msg.setVauth(c.getString(c.getColumnIndex("_vauth")));
				// msg.setPlazaat(c.getInt(c.getColumnIndex("_plaza")) == 1 ?
				// true
				// : false);
				// msg.setIntimateid(c.getString(c.getColumnIndex("_intimateid")));
				// msg.setAnswer(c.getString(c.getColumnIndex("_answer")));

				// 按钮喔
				buttonList = new ArrayList<ButtonInfo>();
				String buttonName = c.getString(c
						.getColumnIndex("_button_name1"));
				String buttonUrl = c
						.getString(c.getColumnIndex("_button_url1"));

				if (!TextUtils.isEmpty(buttonName)
						&& !TextUtils.isEmpty(buttonUrl)) {
					info = new ButtonInfo();
					info.setName(buttonName);
					info.setUrl(buttonUrl);
					buttonList.add(info);
				}
				buttonName = c.getString(c.getColumnIndex("_button_name2"));
				buttonUrl = c.getString(c.getColumnIndex("_button_url2"));

				if (!TextUtils.isEmpty(buttonName)
						&& !TextUtils.isEmpty(buttonUrl)) {
					info = new ButtonInfo();
					info.setName(buttonName);
					info.setUrl(buttonUrl);
					buttonList.add(info);
				}
				msg.setButtonList(buttonList);

				String type = c.getString(c.getColumnIndex("_type"));
				// if (type != null) {
				// if (type.equals("gift")) {
				// msg.setGifts(new Gifts());
				// } else if (type.equals("praise")) {
				// msg.setPraise(new Praise());
				// }
				// }

				try {
					msg.setFileId(c.getString(c.getColumnIndex("_fileId")));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (!list.contains(msg)) {
					list.add(msg);
				}
			}
			msg = null;
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d("MY_MESSAGE_HISTORY中一共有" + list.size() + "条留言!");

		return list;
	}

	/**
	 * 读取与某jid的所有留言
	 * 
	 * @param jid
	 * @return
	 */
	public ArrayList<ALMessage> loadMessageRecordByLeaveActivity(int offset) {
		ArrayList<ALMessage> list = new ArrayList<ALMessage>();

		ButtonInfo info = null;
		ArrayList<ButtonInfo> buttonList = null;

		String[] arg = { ALMessage.GIFT_MESSAGE, ALMessage.PRIASE_MESSAGE,
				ALMessage.PLAZAAT_MESSAGE };
		Cursor c = null;

		String sql = "SELECT * FROM "
				+ MY_MESSAGE_RECORD
				+ " WHERE _type!=? AND _type!=? AND _type!=? ORDER BY _time DESC LIMIT "
				+ DEFAULT_PAGE_COUNT + " offset " + offset;

		try {

			c = db.rawQuery(sql, arg);

		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			ALMessage msg = null;
			while (c.moveToNext()) {
				msg = new ALMessage();

				msg.setFrom(c.getString(c.getColumnIndex("_from")));
				msg.setTo(c.getString(c.getColumnIndex("_to")));
				msg.setFromNick(c.getString(c.getColumnIndex("_fromNick")));
				msg.setToNick(c.getString(c.getColumnIndex("_toNick")));
				msg.setSubject(c.getString(c.getColumnIndex("_subject")));
				msg.setBody(c.getString(c.getColumnIndex("_body")));
				msg.setLinkBody(c.getString(c.getColumnIndex("_body2")));
				msg.setLinkBody2(c.getString(c.getColumnIndex("_body3")));
				msg.setTime(new Date(c.getLong(c.getColumnIndex("_time"))));
				// msg.setDate(new Date(c.getLong(c.getColumnIndex("_time"))));
				msg.setMsgId(c.getString(c.getColumnIndex("_msgId")));
				msg.setJid(c.getString(c.getColumnIndex("_jid")));
				msg.setDisplayed(c.getInt(c.getColumnIndex("_state")) == 1 ? true
						: false);
				// 语音留言
				msg.setAudioFaceId(c.getString(c.getColumnIndex("_audiofileid")));
				
				//性别
				msg.setSex(c.getString(c.getColumnIndex("_sex")));
				//V认证
				msg.setVauth(c.getString(c.getColumnIndex("_vauth")));


				// msg.setPlazaat(c.getInt(c.getColumnIndex("_plaza")) == 1 ?
				// true
				// : false);
				// msg.setIntimateid(c.getString(c.getColumnIndex("_intimateid")));
				// msg.setAnswer(c.getString(c.getColumnIndex("_answer")));

				// String type = c.getString(c.getColumnIndex("_type"));
				// if (type != null) {
				// if (type.equals("gift")) {
				// msg.setGifts(new Gifts());
				// } else if (type.equals("praise")) {
				// msg.setPraise(new Praise());
				// }
				// }

				buttonList = new ArrayList<ButtonInfo>();

				String buttonName = c.getString(c
						.getColumnIndex("_button_name1"));
				String buttonUrl = c
						.getString(c.getColumnIndex("_button_url1"));

				if (!TextUtils.isEmpty(buttonName)
						&& !TextUtils.isEmpty(buttonUrl)) {
					info = new ButtonInfo();
					info.setName(buttonName);
					info.setUrl(buttonUrl);
					buttonList.add(info);
				}
				buttonName = c.getString(c.getColumnIndex("_button_name2"));
				buttonUrl = c.getString(c.getColumnIndex("_button_url2"));

				if (!TextUtils.isEmpty(buttonName)
						&& !TextUtils.isEmpty(buttonUrl)) {
					info = new ButtonInfo();
					info.setName(buttonName);
					info.setUrl(buttonUrl);
					buttonList.add(info);
				}
				msg.setButtonList(buttonList);

				try {
					msg.setFromAvatar(c.getString(c.getColumnIndex("_fileId")));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				ALLog.d("头像id " + msg.getFromAvatar());
				if (!list.contains(msg)) {
					list.add(msg);
				}
			}
			msg = null;
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d("分页中一共有" + list.size() + "条留言!");

		return list;
	}

	/**
	 * 读取与某jid的所有留言
	 * 
	 * @param jid
	 * @return
	 */
	public int loadNumMessageRecordByLeaveActivity() {

		String[] arg = { ALMessage.PRIASE_MESSAGE, ALMessage.PLAZAAT_MESSAGE,
				ALMessage.GIFT_MESSAGE };
		Cursor c = null;

		int count = 0;

		String sql = "SELECT * FROM " + MY_MESSAGE_RECORD
				+ " WHERE _type!=? AND _type!=? AND _type!=?";

		try {

			c = db.rawQuery(sql, arg);

		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			count = c.getCount();
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d("一共有" + count + "条留言!");

		return count;
	}

	/**
	 * 读取与某jid的所有留言
	 * 
	 * @param jid
	 * @return
	 */
	public int loadNumMessageRecordByPraiseActivity() {

		String[] arg = { ALMessage.PRIASE_MESSAGE };
		Cursor c = null;

		int count = 0;

		String sql = "SELECT * FROM " + MY_MESSAGE_RECORD + " WHERE _type=?";

		try {

			c = db.rawQuery(sql, arg);

		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			count = c.getCount();
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d("一共有" + count + "条评价留言!");

		return count;
	}

	/**
	 * 返回礼物消息的条目数量
	 * 
	 * @return
	 */
	public int loadNumMessageRecordByGiftActivity() {

		String[] arg = { ALMessage.GIFT_MESSAGE };
		Cursor c = null;

		int count = 0;

		String sql = "SELECT * FROM " + MY_MESSAGE_RECORD + " WHERE _type=?";

		try {

			c = db.rawQuery(sql, arg);

		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			count = c.getCount();
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d("一共有" + count + "条礼物消息!");

		return count;
	}

	/**
	 * 读取广场at条目的数量
	 * 
	 * @return
	 */
	public int loadNumMessageRecordByPlazaAtActivity() {

		String[] arg = { ALMessage.PLAZAAT_MESSAGE };
		Cursor c = null;

		int count = 0;

		String sql = "SELECT * FROM " + MY_MESSAGE_RECORD + " WHERE _type=?";

		try {

			c = db.rawQuery(sql, arg);

		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			count = c.getCount();
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d("一共有" + count + "条评价留言!");

		return count;
	}

	/**
	 * 读取与某jid的所有留言
	 * 
	 * @param jid
	 * @return
	 */
	public int loadNumMessageRecordBySystemActivity() {

		Cursor c = null;

		int count = 0;

		String sql = "SELECT * FROM " + SYSTEM_MESSAGE;

		try {

			c = db.rawQuery(sql, null);

		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			count = c.getCount();
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d("一共有" + count + "条系统留言!");

		return count;
	}

	/**
	 * 读取与某jid的所有留言
	 * 
	 * @param jid
	 * @return
	 */
	public ArrayList<ALMessage> loadMessageRecord(String contact, int offset) {
		ArrayList<ALMessage> list = new ArrayList<ALMessage>();

		ButtonInfo info = null;
		ArrayList<ButtonInfo> buttonList = null;

		String[] arg = { contact };
		Cursor c = null;

		String sql = "SELECT * FROM " + MY_MESSAGE_RECORD
				+ " WHERE _type=?  ORDER BY _time DESC LIMIT "
				+ DEFAULT_PAGE_COUNT + " offset " + offset;

		try {
			// c = db.rawQuery("SELECT * FROM " + MY_MESSAGE_RECORD
			// + " where _type=?" + " ORDER BY _time DESC", arg);
			c = db.rawQuery(sql, arg);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			ALMessage msg = null;
			while (c.moveToNext()) {
				msg = new ALMessage();

				msg.setFrom(c.getString(c.getColumnIndex("_from")));
				msg.setTo(c.getString(c.getColumnIndex("_to")));
				msg.setFromNick(c.getString(c.getColumnIndex("_fromNick")));
				msg.setToNick(c.getString(c.getColumnIndex("_toNick")));
				msg.setSubject(c.getString(c.getColumnIndex("_subject")));
				msg.setBody(c.getString(c.getColumnIndex("_body")));
				msg.setLinkBody(c.getString(c.getColumnIndex("_body2")));
				msg.setLinkBody2(c.getString(c.getColumnIndex("_body3")));
				msg.setTime(new Date(c.getLong(c.getColumnIndex("_time"))));
				// msg.setDate(new Date(c.getLong(c.getColumnIndex("_time"))));
				msg.setMsgId(c.getString(c.getColumnIndex("_msgId")));
				msg.setJid(c.getString(c.getColumnIndex("_jid")));
				msg.setDisplayed(c.getInt(c.getColumnIndex("_state")) == 1 ? true
						: false);
				// 语音留言
				msg.setAudioFaceId(c.getString(c.getColumnIndex("_audiofileid")));
				
				//性别
				msg.setSex(c.getString(c.getColumnIndex("_sex")));
				//V认证
				msg.setVauth(c.getString(c.getColumnIndex("_vauth")));


				// msg.setPlazaat(c.getInt(c.getColumnIndex("_plaza")) == 1 ?
				// true
				// : false);
				// msg.setIntimateid(c.getString(c.getColumnIndex("_intimateid")));
				// msg.setAnswer(c.getString(c.getColumnIndex("_answer")));

				// String type = c.getString(c.getColumnIndex("_type"));
				// if (type != null) {
				// if (type.equals("gift")) {
				// msg.setGifts(new Gifts());
				// } else if (type.equals("praise")) {
				// msg.setPraise(new Praise());
				// }
				// }

				buttonList = new ArrayList<ButtonInfo>();

				String buttonName = c.getString(c
						.getColumnIndex("_button_name1"));
				String buttonUrl = c
						.getString(c.getColumnIndex("_button_url1"));

				if (!TextUtils.isEmpty(buttonName)
						&& !TextUtils.isEmpty(buttonUrl)) {
					info = new ButtonInfo();
					info.setName(buttonName);
					info.setUrl(buttonUrl);
					buttonList.add(info);
				}
				buttonName = c.getString(c.getColumnIndex("_button_name2"));
				buttonUrl = c.getString(c.getColumnIndex("_button_url2"));

				if (!TextUtils.isEmpty(buttonName)
						&& !TextUtils.isEmpty(buttonUrl)) {
					info = new ButtonInfo();
					info.setName(buttonName);
					info.setUrl(buttonUrl);
					buttonList.add(info);
				}
				msg.setButtonList(buttonList);

				try {
					msg.setFileId(c.getString(c.getColumnIndex("_fileId")));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				ALLog.d("头像id " + msg.getFIleId());
				if (!list.contains(msg)) {
					list.add(msg);
				}
			}
			msg = null;
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d("分页评价中一共有" + list.size() + "条留言!");

		return list;
	}

	/**
	 * 获取某种类型中最近的一条消息
	 * 
	 * @param contact
	 * @return
	 */
	public ALMessage loadMessageNearRecord(String contact) {
		ALMessage msg = null;
		ButtonInfo info = null;
		ArrayList<ButtonInfo> buttonList = null;

		String[] arg = { contact };
		Cursor c = null;

		String sql = "SELECT * FROM " + MY_MESSAGE_RECORD
				+ " WHERE _type=?  ORDER BY _time DESC LIMIT 1";

		try {
			c = db.rawQuery(sql, arg);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			while (c.moveToNext()) {
				msg = new ALMessage();

				msg.setFrom(c.getString(c.getColumnIndex("_from")));
				msg.setTo(c.getString(c.getColumnIndex("_to")));
				msg.setFromNick(c.getString(c.getColumnIndex("_fromNick")));
				msg.setToNick(c.getString(c.getColumnIndex("_toNick")));
				msg.setSubject(c.getString(c.getColumnIndex("_subject")));
				msg.setBody(c.getString(c.getColumnIndex("_body")));
				msg.setLinkBody(c.getString(c.getColumnIndex("_body2")));
				msg.setLinkBody2(c.getString(c.getColumnIndex("_body3")));
				msg.setTime(new Date(c.getLong(c.getColumnIndex("_time"))));
				// msg.setDate(new Date(c.getLong(c.getColumnIndex("_time"))));
				msg.setMsgId(c.getString(c.getColumnIndex("_msgId")));
				msg.setJid(c.getString(c.getColumnIndex("_jid")));
				msg.setDisplayed(c.getInt(c.getColumnIndex("_state")) == 1 ? true
						: false);
				// 语音留言
				msg.setAudioFaceId(c.getString(c.getColumnIndex("_audiofileid")));
				
				//性别
				msg.setSex(c.getString(c.getColumnIndex("_sex")));
				//V认证
				msg.setVauth(c.getString(c.getColumnIndex("_vauth")));


				// msg.setPlazaat(c.getInt(c.getColumnIndex("_plaza")) == 1 ?
				// true
				// : false);
				// msg.setIntimateid(c.getString(c.getColumnIndex("_intimateid")));
				// msg.setAnswer(c.getString(c.getColumnIndex("_answer")));

				// String type = c.getString(c.getColumnIndex("_type"));
				// if (type != null) {
				// if (type.equals("gift")) {
				// msg.setGifts(new Gifts());
				// } else if (type.equals("praise")) {
				// msg.setPraise(new Praise());
				// }
				// }

				buttonList = new ArrayList<ButtonInfo>();

				String buttonName = c.getString(c
						.getColumnIndex("_button_name1"));
				String buttonUrl = c
						.getString(c.getColumnIndex("_button_url1"));

				if (!TextUtils.isEmpty(buttonName)
						&& !TextUtils.isEmpty(buttonUrl)) {
					info = new ButtonInfo();
					info.setName(buttonName);
					info.setUrl(buttonUrl);
					buttonList.add(info);
				}
				buttonName = c.getString(c.getColumnIndex("_button_name2"));
				buttonUrl = c.getString(c.getColumnIndex("_button_url2"));

				if (!TextUtils.isEmpty(buttonName)
						&& !TextUtils.isEmpty(buttonUrl)) {
					info = new ButtonInfo();
					info.setName(buttonName);
					info.setUrl(buttonUrl);
					buttonList.add(info);
				}
				msg.setButtonList(buttonList);

				try {
					msg.setFileId(c.getString(c.getColumnIndex("_fileId")));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				ALLog.d("头像id " + msg.getFIleId());
			}
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d("成功读取到" + contact + "类型的最近一条消息");

		return msg;
	}

	/**
	 * 读取与某jid的所有留言
	 * 
	 * @param jid
	 * @return
	 */
	public ArrayList<ALMessage> loadMessageRecord(String contact) {
		ArrayList<ALMessage> list = new ArrayList<ALMessage>();

		ButtonInfo info = null;
		ArrayList<ButtonInfo> buttonList = null;

		String[] arg = { contact };
		Cursor c = null;
		try {
			c = db.rawQuery("SELECT * FROM " + MY_MESSAGE_RECORD
					+ " where _type=?" + " ORDER BY _time DESC", arg);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			ALMessage msg = null;
			while (c.moveToNext()) {
				msg = new ALMessage();

				msg.setFrom(c.getString(c.getColumnIndex("_from")));
				msg.setTo(c.getString(c.getColumnIndex("_to")));
				msg.setFromNick(c.getString(c.getColumnIndex("_fromNick")));
				msg.setToNick(c.getString(c.getColumnIndex("_toNick")));
				msg.setSubject(c.getString(c.getColumnIndex("_subject")));
				msg.setBody(c.getString(c.getColumnIndex("_body")));
				msg.setLinkBody(c.getString(c.getColumnIndex("_body2")));
				msg.setLinkBody2(c.getString(c.getColumnIndex("_body3")));
				msg.setTime(new Date(c.getLong(c.getColumnIndex("_time"))));
				// msg.setDate(new Date(c.getLong(c.getColumnIndex("_time"))));
				msg.setMsgId(c.getString(c.getColumnIndex("_msgId")));
				msg.setJid(c.getString(c.getColumnIndex("_jid")));
				msg.setDisplayed(c.getInt(c.getColumnIndex("_state")) == 1 ? true
						: false);
				// 语音留言
				msg.setAudioFaceId(c.getString(c.getColumnIndex("_audiofileid")));
				
				//性别
				msg.setSex(c.getString(c.getColumnIndex("_sex")));
				//V认证
				msg.setVauth(c.getString(c.getColumnIndex("_vauth")));


				// msg.setPlazaat(c.getInt(c.getColumnIndex("_plaza")) == 1 ?
				// true
				// : false);
				// msg.setIntimateid(c.getString(c.getColumnIndex("_intimateid")));
				// msg.setAnswer(c.getString(c.getColumnIndex("_answer")));

				// String type = c.getString(c.getColumnIndex("_type"));
				// if (type != null) {
				// if (type.equals("gift")) {
				// msg.setGifts(new Gifts());
				// } else if (type.equals("praise")) {
				// msg.setPraise(new Praise());
				// }
				// }

				buttonList = new ArrayList<ButtonInfo>();

				String buttonName = c.getString(c
						.getColumnIndex("_button_name1"));
				String buttonUrl = c
						.getString(c.getColumnIndex("_button_url1"));

				if (!TextUtils.isEmpty(buttonName)
						&& !TextUtils.isEmpty(buttonUrl)) {
					info = new ButtonInfo();
					info.setName(buttonName);
					info.setUrl(buttonUrl);
					buttonList.add(info);
				}
				buttonName = c.getString(c.getColumnIndex("_button_name2"));
				buttonUrl = c.getString(c.getColumnIndex("_button_url2"));

				if (!TextUtils.isEmpty(buttonName)
						&& !TextUtils.isEmpty(buttonUrl)) {
					info = new ButtonInfo();
					info.setName(buttonName);
					info.setUrl(buttonUrl);
					buttonList.add(info);
				}
				msg.setButtonList(buttonList);

				try {
					msg.setFileId(c.getString(c.getColumnIndex("_fileId")));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				ALLog.d("头像id " + msg.getFIleId());
				if (!list.contains(msg)) {
					list.add(msg);
				}
			}
			msg = null;
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d("MY_MESSAGE_RECORD中一共有" + list.size() + "条留言!");

		return list;
	}

	/**
	 * 读取与某jid的所有留言
	 * 
	 * @param jid
	 * @return
	 */
	public int loadMessageRecordCount() {
		int count = 0;
		Cursor c = null;
		try {
			c = db.rawQuery("SELECT * FROM " + MY_MESSAGE_RECORD
					+ " ORDER BY _time DESC", null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			count = c.getCount();
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d("MY_MESSAGE_RECORD中一共有" + count + "条留言!");

		return count;
	}

	/**
	 * 读取与某jid的所有留言
	 * 
	 * @param jid
	 * @return
	 */
	public ArrayList<ALMessage> loadMessageRecordByJidAsTime(String jid) {
		ArrayList<ALMessage> list = new ArrayList<ALMessage>();
		String[] args = { jid };

		ButtonInfo info = null;
		ArrayList<ButtonInfo> buttonList = null;
		Cursor c = null;
		try {
			c = db.rawQuery("SELECT * FROM " + MY_MESSAGE_RECORD
					+ " where _jid=? ORDER BY _time", args);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			ALMessage msg = null;
			while (c.moveToNext()) {
				msg = new ALMessage();

				msg.setFrom(c.getString(c.getColumnIndex("_from")));
				msg.setTo(c.getString(c.getColumnIndex("_to")));
				msg.setFromNick(c.getString(c.getColumnIndex("_fromNick")));
				msg.setToNick(c.getString(c.getColumnIndex("_toNick")));
				msg.setSubject(c.getString(c.getColumnIndex("_subject")));
				msg.setBody(c.getString(c.getColumnIndex("_body")));
				msg.setLinkBody(c.getString(c.getColumnIndex("_body2")));
				msg.setLinkBody2(c.getString(c.getColumnIndex("_body3")));
				msg.setTime(new Date(c.getLong(c.getColumnIndex("_time"))));
				// msg.setDate(new Date(c.getLong(c.getColumnIndex("_time"))));
				msg.setMsgId(c.getString(c.getColumnIndex("_msgId")));
				msg.setJid(c.getString(c.getColumnIndex("_jid")));
				msg.setDisplayed(c.getInt(c.getColumnIndex("_state")) == 1 ? true
						: false);
				// 语音留言
				msg.setAudioFaceId(c.getString(c.getColumnIndex("_audiofileid")));
				//性别
				msg.setSex(c.getString(c.getColumnIndex("_sex")));
				//V认证
				msg.setVauth(c.getString(c.getColumnIndex("_vauth")));


				// msg.setPlazaat(c.getInt(c.getColumnIndex("_plaza")) == 1 ?
				// true
				// : false);
				// msg.setIntimateid(c.getString(c.getColumnIndex("_intimateid")));
				// msg.setAnswer(c.getString(c.getColumnIndex("_answer")));

				// String type = c.getString(c.getColumnIndex("_type"));
				// if (type != null) {
				// if (type.equals("gift")) {
				// msg.setGifts(new Gifts());
				// } else if (type.equals("praise")) {
				// msg.setPraise(new Praise());
				// }
				// }
				buttonList = new ArrayList<ButtonInfo>();

				String buttonName = c.getString(c
						.getColumnIndex("_button_name1"));
				String buttonUrl = c
						.getString(c.getColumnIndex("_button_url1"));

				if (!TextUtils.isEmpty(buttonName)
						&& !TextUtils.isEmpty(buttonUrl)) {
					info = new ButtonInfo();
					info.setName(buttonName);
					info.setUrl(buttonUrl);
					buttonList.add(info);
				}
				buttonName = c.getString(c.getColumnIndex("_button_name2"));
				buttonUrl = c.getString(c.getColumnIndex("_button_url2"));

				if (!TextUtils.isEmpty(buttonName)
						&& !TextUtils.isEmpty(buttonUrl)) {
					info = new ButtonInfo();
					info.setName(buttonName);
					info.setUrl(buttonUrl);
					buttonList.add(info);
				}
				msg.setButtonList(buttonList);

				try {
					msg.setFileId(c.getString(c.getColumnIndex("_fileId")));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (!list.contains(msg)) {
					list.add(msg);
				}
			}
			msg = null;
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d("MY_MESSAGE_HISTORY中一共有" + list.size() + "条留言!");

		return list;
	}

	/**
	 * 读取与某jid的所有未读留言
	 * 
	 * @param jid
	 * @return
	 */
	public ArrayList<ALMessage> loadUnreadMessageListByJid(String jid) {
		ArrayList<ALMessage> list = new ArrayList<ALMessage>();
		String[] args = { jid };
		Cursor c = null;

		ButtonInfo info = null;
		ArrayList<ButtonInfo> buttonList = null;

		try {
			c = db.rawQuery("SELECT * FROM " + MY_MESSAGE_RECORD
					+ " where _state=0 and _jid=?", args);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			ALMessage msg = null;
			while (c.moveToNext()) {
				msg = new ALMessage();

				msg.setFrom(c.getString(c.getColumnIndex("_from")));
				msg.setTo(c.getString(c.getColumnIndex("_to")));
				msg.setFromNick(c.getString(c.getColumnIndex("_fromNick")));
				msg.setToNick(c.getString(c.getColumnIndex("_toNick")));
				msg.setSubject(c.getString(c.getColumnIndex("_subject")));
				msg.setBody(c.getString(c.getColumnIndex("_body")));
				msg.setLinkBody(c.getString(c.getColumnIndex("_body2")));
				msg.setLinkBody2(c.getString(c.getColumnIndex("_body3")));
				msg.setTime(new Date(c.getLong(c.getColumnIndex("_time"))));
				// msg.setDate(new Date(c.getLong(c.getColumnIndex("_time"))));
				msg.setMsgId(c.getString(c.getColumnIndex("_msgId")));
				msg.setJid(c.getString(c.getColumnIndex("_jid")));
				msg.setDisplayed(c.getInt(c.getColumnIndex("_state")) == 1 ? true
						: false);
				// 语音留言
				msg.setAudioFaceId(c.getString(c.getColumnIndex("_audiofileid")));
				//性别
				msg.setSex(c.getString(c.getColumnIndex("_sex")));
				//V认证
				msg.setVauth(c.getString(c.getColumnIndex("_vauth")));


				// msg.setPlazaat(c.getInt(c.getColumnIndex("_plaza")) == 1 ?
				// true
				// : false);
				// msg.setIntimateid(c.getString(c.getColumnIndex("_intimateid")));
				// msg.setAnswer(c.getString(c.getColumnIndex("_answer")));

				// String type = c.getString(c.getColumnIndex("_type"));
				// if (type != null) {
				// if (type.equals("gift")) {
				// msg.setGifts(new Gifts());
				// } else if (type.equals("praise")) {
				// msg.setPraise(new Praise());
				// }
				// }

				buttonList = new ArrayList<ButtonInfo>();

				String buttonName = c.getString(c
						.getColumnIndex("_button_name1"));
				String buttonUrl = c
						.getString(c.getColumnIndex("_button_url1"));

				if (!TextUtils.isEmpty(buttonName)
						&& !TextUtils.isEmpty(buttonUrl)) {
					info = new ButtonInfo();
					info.setName(buttonName);
					info.setUrl(buttonUrl);
					buttonList.add(info);
				}
				buttonName = c.getString(c.getColumnIndex("_button_name2"));
				buttonUrl = c.getString(c.getColumnIndex("_button_url2"));

				if (!TextUtils.isEmpty(buttonName)
						&& !TextUtils.isEmpty(buttonUrl)) {
					info = new ButtonInfo();
					info.setName(buttonName);
					info.setUrl(buttonUrl);
					buttonList.add(info);
				}
				msg.setButtonList(buttonList);

				try {
					msg.setFileId(c.getString(c.getColumnIndex("_fileId")));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (!list.contains(msg)) {
					list.add(msg);
				}
			}
			msg = null;
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d("MY_MESSAGE_HISTORY中一共有" + list.size() + "条未读留言!");

		return list;
	}

	/**
	 * 读取所有未读留言
	 * 
	 * @param jid
	 * @return
	 */
	public ArrayList<ALMessage> loadUnreadMessageList() {
		ArrayList<ALMessage> list = new ArrayList<ALMessage>();

		Cursor c = null;
		ButtonInfo info = null;
		ArrayList<ButtonInfo> buttonList = null;

		try {
			c = db.rawQuery("SELECT * FROM " + MY_MESSAGE_RECORD
					+ " where _state=0 ", null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			ALMessage msg = null;
			while (c.moveToNext()) {
				msg = new ALMessage();

				msg.setFrom(c.getString(c.getColumnIndex("_from")));
				msg.setTo(c.getString(c.getColumnIndex("_to")));
				msg.setFromNick(c.getString(c.getColumnIndex("_fromNick")));
				msg.setToNick(c.getString(c.getColumnIndex("_toNick")));
				msg.setSubject(c.getString(c.getColumnIndex("_subject")));
				msg.setBody(c.getString(c.getColumnIndex("_body")));
				msg.setLinkBody(c.getString(c.getColumnIndex("_body2")));
				msg.setLinkBody2(c.getString(c.getColumnIndex("_body3")));
				msg.setTime(new Date(c.getLong(c.getColumnIndex("_time"))));
				// msg.setDate(new Date(c.getLong(c.getColumnIndex("_time"))));
				msg.setMsgId(c.getString(c.getColumnIndex("_msgId")));
				msg.setJid(c.getString(c.getColumnIndex("_jid")));
				msg.setDisplayed(c.getInt(c.getColumnIndex("_state")) == 1 ? true
						: false);
				// 语音留言
				msg.setAudioFaceId(c.getString(c.getColumnIndex("_audiofileid")));
				//性别
				msg.setSex(c.getString(c.getColumnIndex("_sex")));
				//V认证
				msg.setVauth(c.getString(c.getColumnIndex("_vauth")));


				// msg.setPlazaat(c.getInt(c.getColumnIndex("_plaza")) == 1 ?
				// true
				// : false);
				// msg.setIntimateid(c.getString(c.getColumnIndex("_intimateid")));
				// msg.setAnswer(c.getString(c.getColumnIndex("_answer")));
				//
				// String type = c.getString(c.getColumnIndex("_type"));
				// if (type != null) {
				// if (type.equals("gift")) {
				// msg.setGifts(new Gifts());
				// } else if (type.equals("praise")) {
				// msg.setPraise(new Praise());
				// }
				// }

				try {
					msg.setFileId(c.getString(c.getColumnIndex("_fileId")));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				buttonList = new ArrayList<ButtonInfo>();

				String buttonName = c.getString(c
						.getColumnIndex("_button_name1"));
				String buttonUrl = c
						.getString(c.getColumnIndex("_button_url1"));

				if (!TextUtils.isEmpty(buttonName)
						&& !TextUtils.isEmpty(buttonUrl)) {
					info = new ButtonInfo();
					info.setName(buttonName);
					info.setUrl(buttonUrl);
					buttonList.add(info);
				}
				buttonName = c.getString(c.getColumnIndex("_button_name2"));
				buttonUrl = c.getString(c.getColumnIndex("_button_url2"));

				if (!TextUtils.isEmpty(buttonName)
						&& !TextUtils.isEmpty(buttonUrl)) {
					info = new ButtonInfo();
					info.setName(buttonName);
					info.setUrl(buttonUrl);
					buttonList.add(info);
				}
				msg.setButtonList(buttonList);

				if (!list.contains(msg)) {
					list.add(msg);
				}
			}
			msg = null;
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d("MY_MESSAGE_RECORD中一共有" + list.size() + "条未读留言!");

		return list;
	}

	/**
	 * 将指定id的留言设为已读
	 * 
	 * @param msgid
	 */
	public void setMessageRecordIsReadedByMsgId(String msgid) {
		String[] arg = { msgid };
		ContentValues values = new ContentValues();
		values.put("_state", 1);

		if (db.update(MY_MESSAGE_RECORD, values, "_msgId=?", arg) > 0) {
			ALLog.d("设定msgid为" + msgid + "的留言为已读！");
			return;
		}
		return;
	}

	/**
	 * 保存收到的留言记录
	 * 
	 * @param msg
	 */
	public void saveMessageRecord(ALMessage msg) {
		ContentValues values = new ContentValues();
		values.put("_from", msg.getFrom());
		values.put("_to", msg.getTo());
		values.put("_fromNick", msg.getFromNick());
		values.put("_toNick", msg.getToNick());
		values.put("_subject", msg.getSubject());
		values.put("_body", msg.getBody());
		values.put("_body2", msg.getLinkBody());
		values.put("_body3", msg.getLinkBody2());
		values.put("_msgId", msg.getMsgId());
		values.put("_time", msg.getTime().getTime());
		values.put("_jid", msg.getJid());
		// 头像
		values.put("_fileId", msg.getFromAvatar());

		// 语音留言
		values.put("_audiofileid", msg.getAudioFaceId());
		//性别
		values.put("_sex", msg.getSex());
		//V认证
		values.put("_vauth", msg.getVauth());

		// 根据已读状态，写入数据库
		if (msg.getDisplayed()) {
			values.put("_state", 1);
		} else {
			values.put("_state", 0);
		}
		// if (msg.isPlazaat()) {
		// values.put("_plaza", 1);
		// } else {
		// values.put("_plaza", 0);
		// }

		// if (msg.getGifts() != null) {
		// values.put("_type", ALMessage.GIFT_MESSAGE);
		// } else if (msg.getPraise() != null) {
		// values.put("_type", ALMessage.PRIASE_MESSAGE);
		// } else if (msg.isPlazaat()) {
		// values.put("_type", ALMessage.PLAZAAT_MESSAGE);
		// } else if (msg.getIntimateid() != null) {
		// values.put("_type", ALMessage.INVITE_MESSAGE);
		// } else {
		// values.put("_type", ALMessage.LEAVE_MESSAGE);
		// }

		values.put("_type", msg.getMsgType());

		if (msg.getButtonList() != null && msg.getButtonList().size() > 0) {

			ButtonInfo info = new ButtonInfo();

			for (int i = 0; i < msg.getButtonList().size(); i++) {
				info = msg.getButtonList().get(i);
				values.put("_button_url" + (i + 1), info.getUrl());
				values.put("_button_name" + (i + 1), info.getName());
			}
		}

		if (db.insert(MY_MESSAGE_RECORD, "", values) == -1) {
			ALLog.d("保存与" + msg.getJid() + "的留言失败");
			return;
		}
		ALLog.d("保存与" + msg.getJid() + "的留言成功" + msg.getMsgId());
	}

	public String getLeaveMessageTypeById(String id) {
		Cursor c = null;
		String[] args = { id };
		String type = null;
		try {

			c = db.rawQuery("SELECT * FROM " + MY_MESSAGE_RECORD
					+ " where _msgId=? ", args);

		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			while (c.moveToNext()) {

				type = c.getString(c.getColumnIndex("_type"));
			}
			try {
				c.close();
			} catch (Exception e) {
			}
		}
		ALLog.d("类型是什么" + type);
		return type;
	}

	/**
	 * 读取与某jid的所有留言
	 * 
	 * @param jid
	 * @return
	 */
	public void updateAllMessageRecordType() {

		Cursor c = null;
		try {
			c = db.rawQuery("SELECT * FROM " + MY_MESSAGE_RECORD
					+ " ORDER BY _time DESC", null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			while (c.moveToNext()) {
				String msgId = c.getString(c.getColumnIndex("_msgId"));
				boolean isPlazaat = c.getInt(c.getColumnIndex("_plaza")) == 1 ? true
						: false;
				String type = c.getString(c.getColumnIndex("_type"));

				if (type != null) {
					if (isPlazaat) {
						updateLeavMessageType(msgId, ALMessage.PLAZAAT_MESSAGE);
					} else if (type.equals(ALMessage.GIFT_MESSAGE)) {
						updateLeavMessageType(msgId, ALMessage.GIFT_MESSAGE);
					} else if (type.equals(ALMessage.PRIASE_MESSAGE)) {
						updateLeavMessageType(msgId, ALMessage.PRIASE_MESSAGE);
					} else {
						updateLeavMessageType(msgId, ALMessage.LEAVE_MESSAGE);
					}
				} else {
					if (isPlazaat) {
						updateLeavMessageType(msgId, ALMessage.PLAZAAT_MESSAGE);
					} else {
						updateLeavMessageType(msgId, ALMessage.LEAVE_MESSAGE);
					}
				}

			}
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

	}

	public void updateLeavMessageType(String msgid, String type) {
		String[] arg = { msgid };
		ContentValues values = new ContentValues();
		values.put("_type", type);

		if (db.update(MY_MESSAGE_RECORD, values, "_msgId=?", arg) > 0) {
		}
	}

	public boolean isLeaveMessageTypeNull() {
		Cursor c = null;
		c = db.rawQuery("SELECT * FROM " + MY_MESSAGE_RECORD, null);
		try {
			if (c != null && c.getCount() > 0) {
				if (c.moveToNext()) {
					for (int i = 0; i < c.getColumnCount(); ++i) {
						if (c.isNull(i)) {
							String columnName = c.getColumnName(i);
							if (!TextUtils.isEmpty(columnName)) {
								if (columnName.equals("_type")) {
									return true;
								}
							}
						}
					}
				}
			}

		} catch (Throwable t) {
			ALLog.d(t.toString());
		} finally {
			if (c != null) {
				try {
					c.close();
				} catch (Exception e) {
				}
			}
		}

		return false;
	}

	public boolean isMessageRecordExsitById(String id) {
		boolean result = false;
		Cursor c = null;
		String[] args = { id };
		try {

			c = db.rawQuery("SELECT * FROM " + MY_MESSAGE_RECORD
					+ " where _msgId=? ", args);

		} catch (Throwable t) {
			ALLog.d(t.toString());
		}
		if (c != null) {
			int i = c.getCount();
			if (i > 0) {
				result = true;
			}
			c.close();
		}
		return result;

	}

	/**
	 * 保存配置信息到本地
	 * 
	 * @param configure
	 */
	public void saveLocalConfigure(LocalConfigure configure) {
		if (configure == null) {
			ALLog.d("你妹的！传个空的对象给我，存个毛线啊！");
			return;
		}

		ContentValues values = new ContentValues();
		// 经纬度
		values.put("_lat", configure.getLat());
		values.put("_lng", configure.getLng());
		// 服务器地址
		values.put("_imip", configure.getServerInfo().getIMServerIP());
		values.put("_import", configure.getServerInfo().getIMSocketPort());
		values.put("_domain", configure.getServerInfo().getServerName());
		values.put("_imhttpport", configure.getServerInfo().getHttpPort());
		values.put("_mediaip", configure.getServerInfo().getMediaServerIp());
		values.put("_mediaport", configure.getServerInfo().getMediaServerPort());
		values.put("_newsurl", configure.getServerInfo().getNewsUrl());

		if (db.insert(LOCAL_CONFIGURE, "", values) == -1) {
			ALLog.d("保存配置信息失败");
			return;
		}
		ALLog.d("保存配置信息成功");

	}

	/**
	 * 读取本地配置信息
	 * 
	 * @return
	 */
	public LocalConfigure getLocalConfigure() {
		LocalConfigure configure = new LocalConfigure();
		ServerInfo info = new ServerInfo();

		Cursor c = null;

		try {
			c = db.rawQuery("SELECT * FROM " + LOCAL_CONFIGURE, null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			while (c.moveToNext()) {
				configure.setLat(c.getString(c.getColumnIndex("_lat")));
				configure.setLng(c.getString(c.getColumnIndex("_lng")));
				info.setIMServerIP(c.getString(c.getColumnIndex("_imip")));
				info.setIMSocketPort(c.getString(c.getColumnIndex("_import")));
				info.setServerName(c.getString(c.getColumnIndex("_domain")));
				info.setHttpPort(c.getString(c.getColumnIndex("_imhttpport")));
				info.setMediaServerIp(c.getString(c.getColumnIndex("_mediaip")));
				info.setMediaServerPort(c.getString(c
						.getColumnIndex("_mediaport")));
				info.setNewsUrl(c.getString(c.getColumnIndex("_newsurl")));
			}
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}
		configure.setServerInfo(info);
		return configure;
	}

	/**
	 * 保存被收藏消息
	 * 
	 * @param ALMessage
	 */
	public void saveFavotiteMessage(ALMessage msg) {
		if (msg == null) {
			ALLog.d("你妹的！传个空的对象给我，存个毛线啊！");
			return;
		}

		ContentValues values = new ContentValues();
		// 发送消息者,消息内容
		values.put("_from", msg.getJid());
		values.put("_body", msg.getBody());

		if (db.insert(FAVOTITE_HISTORY, "", values) == -1) {
			ALLog.d("保存被收藏信息失败");
			return;
		}
		ALLog.d("保存被收藏信息成功");

	}

	/**
	 * 获取指定jid的被收藏消息记录
	 * 
	 * @param jid
	 * @return 被收藏消息记录，若没有则为null
	 */
	public ALMessage getFavotiteMessageByJid(String jid) {
		if (TextUtils.isEmpty(jid)) {
			ALLog.d("没有jid就不找给你！");
			return null;
		}

		ALMessage data = null;
		Cursor c = null;

		String[] args = { jid };

		try {
			c = db.rawQuery("SELECT * FROM " + FAVOTITE_HISTORY
					+ " WHERE _from=?", args);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			if (c.moveToNext()) {
				data = new ALMessage();
				data.setJid(c.getString(c.getColumnIndex("_from")));
				data.setBody(c.getString(c.getColumnIndex("_body")));
			}
		}

		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d((data == null ? "没有" : "") + "找到jid为" + jid + "的被收藏消息记录!");

		return data;
	}

	/**
	 * 获取用户被收藏的次数
	 * 
	 * @return count
	 */
	public int getFavotiteHistoryCount() {
		int count = 0;
		Cursor c = null;

		String sql = "select count(*) as counts from  " + FAVOTITE_HISTORY;
		try {
			c = db.rawQuery(sql, null);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		if (c != null && c.getCount() > 0) {

			while (c.moveToNext()) {
				count = c.getInt(c.getColumnIndex("counts"));
			}
		}

		if (c != null) {
			c.close();
		}

		ALLog.d("该用户被收藏的次数 count:" + count);
		return count;
	}

	/**
	 * 删除被收藏的消息记录
	 * 
	 * @return
	 */
	public void delFavotiteHistory() {
		int count = 0;
		try {
			count = db.delete(FAVOTITE_HISTORY, null, null);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		ALLog.d("删除了用户被收藏额记录 count:" + count);
	}

	/**
	 * 根据jid删除我的粉丝
	 * 
	 * @param jid
	 */
	public void deleteFavotiteHistoryById(String jid) {
		db.delete(FAVOTITE_HISTORY, " _from=?", new String[] { jid });
	}

	public int getAllDateRecordCount() {
		int i = 0;
		Cursor c = null;
		try {
			c = db.rawQuery("SELECT * FROM " + DATING_RECORD, null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}
		if (c != null) {
			i = c.getCount();
			c.close();
		}
		return i;
	}

	/**
	 * 获取所有约会记录
	 * 
	 * @return 所有约会记录列表
	 */
	public ArrayList<DateRecords> getAllDateRecord() {
		ArrayList<DateRecords> list = new ArrayList<DateRecords>();
		Cursor c = null;

		ALLog.d("一共有" + list.size() + "个不在约会的约会记录!");
		try {
			c = db.rawQuery("SELECT * FROM " + DATING_RECORD, null);
			ArrayList<DateRecords> temp = loadDateRecordFromCursor(c);
			list.addAll(temp);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		} finally {
			if (c != null) {
				try {
					c.close();
				} catch (Exception e) {
				}
			}
		}

		ALLog.d("一共有" + list.size() + "个约会记录!");

		return list;
	}

	/**
	 * 获取约会记录总数
	 * 
	 * @param isAppointting
	 * @return
	 */
	public int getDateRecordByStatusCount(boolean isAppointting) {
		int result = 0;
		Cursor c = null;
		String where = " WHERE _isAppointting=" + (isAppointting ? "1" : "0");
		try {
			c = db.rawQuery("SELECT count(*) as counts FROM " + DATING_RECORD
					+ where, null);
			if (c != null) {
				if (c.moveToNext()) {
					result = c.getInt(c.getColumnIndex("counts"));
				}
			}
		} catch (Throwable t) {
		} finally {
			if (c != null) {
				try {
					c.close();
				} catch (Exception e) {
				}
			}
		}
		return result;
	}

	/**
	 * 获取约会记录
	 * 
	 * @param isAppointting
	 *            是否正在约会
	 * @return 约会记录列表
	 */
	public ArrayList<DateRecords> getDateRecordByStatus(boolean isAppointting,
			int offset) {
		ArrayList<DateRecords> list = new ArrayList<DateRecords>();
		Cursor c = null;

		String where = " WHERE _isAppointting=" + (isAppointting ? "1" : "0");
		if (offset >= 0) {
			where += " ORDER BY _isExistUnreadMsg DESC,_time DESC LIMIT "
					+ (offset + 1) * DEFAULT_PAGE_COUNT;
		}
		ALLog.d("一共有" + list.size() + "个不在约会的约会记录!");
		try {
			c = db.rawQuery("SELECT * FROM " + DATING_RECORD + where, null);
			ArrayList<DateRecords> temp = loadDateRecordFromCursor(c);
			list.addAll(temp);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		} finally {
			if (c != null) {
				try {
					c.close();
				} catch (Exception e) {
				}
			}
		}

		ALLog.d("一共有" + list.size() + "个" + (isAppointting ? "正" : "不")
				+ "在约会的约会记录!");

		return list;
	}

	private ArrayList<DateRecords> loadDateRecordFromCursor(Cursor c) {
		ArrayList<DateRecords> list = new ArrayList<DateRecords>();
		DateRecords date = null;

		if (c != null && c.getCount() > 0) {
			while (c.moveToNext()) {

				date = new DateRecords();
				date.setJid(c.getString(c.getColumnIndex("_jid")));
				date.setNick(c.getString(c.getColumnIndex("_nick")));
				date.setIsVip(c.getInt(c.getColumnIndex("_isVip")) != 0);

				date.setImageFileId(c.getString(c
						.getColumnIndex("_imageFileid")));
				date.setDatePlace(c.getString(c.getColumnIndex("_place")));
				date.setDateTime(c.getLong(c.getColumnIndex("_time")));
				date.setDuration(c.getString(c.getColumnIndex("_duration")));
				date.setScene(c.getString(c.getColumnIndex("_scene")));
				date.setsceneName(c.getString(c.getColumnIndex("_sceneName")));
				date.setSex(c.getString(c.getColumnIndex("_sex")));
				date.setDistance(c.getString(c.getColumnIndex("_distance")));
				date.setUserPopularity(c.getString(c
						.getColumnIndex("_userPopularity")));
				date.setStatus(c.getInt(c.getColumnIndex("_status")));
				date.setBirthDay(c.getString(c.getColumnIndex("_birthday")));
				date.setAppointtingState(c.getInt(c
						.getColumnIndex("_isAppointting")) != 0);
				date.setIsExistUnreadMsg(c.getInt(c
						.getColumnIndex("_isExistUnreadMsg")) != 0);
				date.setLastMsgTime(c.getLong(c.getColumnIndex("_lastMsgTime")));
				date.setViplevel(c.getString(c.getColumnIndex("_viplevel")));
				date.setLastRerordContact(c.getString(c
						.getColumnIndex("_lastRecord")));
				date.setLastMsg(c.getString(c.getColumnIndex("_lastMsg")));

				date.setCustomScene(c.getString(c
						.getColumnIndex("_customScene")));
				// 名人
				date.setStarState(c.getInt(c.getColumnIndex("_star")));

				// // ball id
				// String ballid = c.getString(c.getColumnIndex("_ballid"));
				// if (!TextUtils.isEmpty(ballid)) {
				// ALLog.d( "保存由绣球进来的" + ballid);
				// // 创建约会类型为绣球
				// Ball b = new Ball();
				// b.setBallid(ballid);
				// date.setBall(b);
				// }

				date.setResponsed(c.getInt(c.getColumnIndex("_responsed")) != 0);

				date.setCreateType(c.getInt(c.getColumnIndex("_createType")));
				ALLog.d("创建类型为 " + date.getCreateType());

				if (!list.contains(date)) {
					list.add(date);
				}
			}
			date = null;
		}

		return list;
	}

	/**
	 * 获取指定jid的约会记录
	 * 
	 * @param jid
	 * @return 约会记录，若没有则为null
	 */
	public DateRecords getDateRecordByJid(String jid) {
		if (TextUtils.isEmpty(jid)) {
			ALLog.d("没有jid就不找给你！");
			return null;
		}

		DateRecords date = null;
		Cursor c = null;

		String[] args = { jid };

		try {
			c = db.rawQuery("SELECT * FROM " + DATING_RECORD + " WHERE _jid=?",
					args);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			if (c.moveToNext()) {

				date = new DateRecords();
				date.setJid(c.getString(c.getColumnIndex("_jid")));
				date.setNick(c.getString(c.getColumnIndex("_nick")));
				date.setIsVip(c.getInt(c.getColumnIndex("_isVip")) != 0);

				date.setImageFileId(c.getString(c
						.getColumnIndex("_imageFileid")));
				date.setDatePlace(c.getString(c.getColumnIndex("_place")));
				date.setDateTime(c.getLong(c.getColumnIndex("_time")));
				date.setDuration(c.getString(c.getColumnIndex("_duration")));
				date.setScene(c.getString(c.getColumnIndex("_scene")));
				date.setsceneName(c.getString(c.getColumnIndex("_sceneName")));
				date.setSex(c.getString(c.getColumnIndex("_sex")));
				date.setDistance(c.getString(c.getColumnIndex("_distance")));
				date.setUserPopularity(c.getString(c
						.getColumnIndex("_userPopularity")));
				date.setStatus(c.getInt(c.getColumnIndex("_status")));
				date.setBirthDay(c.getString(c.getColumnIndex("_birthday")));
				date.setAppointtingState(c.getInt(c
						.getColumnIndex("_isAppointting")) != 0);
				date.setIsExistUnreadMsg(c.getInt(c
						.getColumnIndex("_isExistUnreadMsg")) != 0);
				date.setLastMsgTime(c.getLong(c.getColumnIndex("_lastMsgTime")));
				date.setViplevel(c.getString(c.getColumnIndex("_viplevel")));
				date.setLastRerordContact(c.getString(c
						.getColumnIndex("_lastRecord")));
				// _customScene
				date.setCustomScene(c.getString(c
						.getColumnIndex("_customScene")));
				// 名人
				date.setStarState(c.getInt(c.getColumnIndex("_star")));
				// 最后一条消息
				date.setLastMsg(c.getString(c.getColumnIndex("_lastMsg")));
				// // ball id
				// String ballid = c.getString(c.getColumnIndex("_ballid"));
				// if (!TextUtils.isEmpty(ballid)) {
				// ALLog.d( "保存由绣球进来的" + ballid);
				// // 创建约会类型为绣球
				// Ball b = new Ball();
				// b.setBallid(ballid);
				// date.setBall(b);
				// }

				date.setCreateType(c.getInt(c.getColumnIndex("_createType")));
				ALLog.d("创建类型为 " + date.getCreateType());

				date.setResponsed(c.getInt(c.getColumnIndex("_responsed")) != 0);

			}
		}

		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d((date == null ? "没有" : "") + "找到jid为" + jid + "的约会记录!");

		return date;
	}

	/**
	 * 是否有正在约会的记录
	 * 
	 * @return true 有; false 没有
	 */
	public boolean isExistAppointtingDateRecords() {
		boolean isExist = false;

		Cursor c = null;

		try {
			c = db.rawQuery("select 1 from " + DATING_RECORD
					+ " where _isAppointting=1", null);
		} catch (Throwable t) {
			t.printStackTrace();
		}

		if ((c != null) && (c.getCount() > 0)) {
			isExist = true;
		}

		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d((isExist ? "有" : "没有") + "正在约会的记录");
		return isExist;
	}

	/**
	 * 保存约会记录
	 * 
	 * @param date
	 */
	public void saveDateRecord(DateRecords date) {
		if (date == null) {
			ALLog.d("你妹的！传个空的对象给我，存个毛线啊！");
			return;
		}

		if (TextUtils.isEmpty(date.getJid())) {
			ALLog.d("没有jid就洗洗睡了，存了也白存！");
			return;
		}

		deleteDateRecordByJid(date.getJid());

		ContentValues values = new ContentValues();
		values.put("_jid", date.getJid());
		values.put("_nick", date.getNick());
		values.put("_isVip", date.isVip() ? 1 : 0);
		values.put("_imageFileid", date.getImageFileId());
		values.put("_place", date.getDatePlace());
		values.put("_time", date.getDateTime());
		values.put("_duration", date.getDuration());
		values.put("_scene", date.getScene());
		values.put("_sceneName", date.getSceneName());
		values.put("_sex", date.getSex());
		values.put("_distance", date.getDistance());
		values.put("_userPopularity", date.getUserPopularity());
		values.put("_status", date.getStatus());
		values.put("_birthday", date.getBirthDay());
		values.put("_isAppointting", date.isAppointting() ? 1 : 0);
		values.put("_viplevel", date.getViplevel());
		values.put("_lastRecord", date.getLastRerordContact());
		values.put("_customScene", date.getCustomScene());
		values.put("_star", date.getStarState());
		// if (date.getBall() != null
		// && !TextUtils.isEmpty(date.getBall().getBallid())) {
		// values.put("_ballid", date.getBall().getBallid());
		// ALLog.d( "保存由绣球进来的");
		// // 创建约会类型为绣球
		// }

		values.put("_createType", date.getCreateType());

		values.put("_responsed", date.isResponsed() ? 1 : 0);

		int isExistUnreadMsg = getUnreadMessageCountByJid(date.getJid()) > 0 ? 1
				: 0;
		values.put("_lastMsg", date.getLastMsg());

		String[] args = { date.getJid() };
		Cursor c = null;
		try {
			c = db.rawQuery("SELECT _time FROM " + MY_DATE_RECORDS_MESSAGE
					+ " WHERE _jid=? ORDER BY _time DESC", args);
		} catch (Throwable t) {
			t.printStackTrace();
		}

		if ((c != null) && (c.getCount() > 0) && c.moveToNext()) {
			ALLog.d("居然有聊天记录");
			Date msgTime = new Date(c.getLong(c.getColumnIndex("_time")));
			values.put("_lastMsgTime", msgTime.getTime());
			values.put("_isExistMsg", 1);
			values.put("_isExistUnreadMsg", isExistUnreadMsg);
		} else {
			ALLog.d("没有聊天记录");
			values.put("_lastMsgTime", 0);
			values.put("_isExistMsg", 0);
			values.put("_isExistUnreadMsg", 0);
		}

		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		if (db.insert(DATING_RECORD, "", values) == -1) {
			ALLog.d("保存约会记录失败");
			return;
		}
		ALLog.d("保存与" + date.getNick() + "约会记录成功");
	}

	/**
	 * 删除多个约会记录
	 * 
	 * @param jids
	 */
	public void deleteDateRecordByJids(ArrayList<String> jids) {
		if (jids == null || jids.size() == 0) {
			return;
		}
		for (String jid : jids) {
			deleteDateRecordByJid(jid);
		}
	}

	/**
	 * 删除指定jid的约会记录
	 * 
	 * @param jid
	 */
	public void deleteDateRecordByJid(String jid) {
		if (TextUtils.isEmpty(jid)) {
			ALLog.d("没有jid就不给你删除！");
			return;
		}

		String[] args = { jid };
		db.delete(DATING_RECORD, ("_jid=?"), args);
	}

	/**
	 * 设置所有约会记录的状态
	 * 
	 * @param isAppointting
	 *            : true正在约会; false不在约会
	 */
	public void setAllDateRecordAppointting(boolean isAppointting) {
		ContentValues values = new ContentValues();
		if (isAppointting) {
			values.put("_isAppointting", 1);
		} else {
			values.put("_isAppointting", 0);
		}

		try {
			db.update(DATING_RECORD, values, null, null);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 设置指定约会记录的状态
	 * 
	 * @param jid
	 *            ： 要修改的约会记录jid
	 * @param isAppointting
	 *            ： true正在约会; false不在约会
	 */
	public void setDateRecordAppointting(String jid, boolean isAppointting) {
		if (TextUtils.isEmpty(jid)) {
			ALLog.d("没有jid就不给你修改！");
			return;
		}

		String[] args = { jid };
		ContentValues values = new ContentValues();
		if (isAppointting) {
			values.put("_isAppointting", 1);
		} else {
			values.put("_isAppointting", 0);
		}

		db.update(DATING_RECORD, values, "_jid=?", args);
	}

	/**
	 * 
	 * @Title: setDateRecordAppointting
	 * @Description: 修改约会记录最后信息
	 * @param @param jid
	 * @param @param isAppointting 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	public void updateDateRecordContact(String lastContact, String jid) {
		if (TextUtils.isEmpty(jid)) {
			ALLog.d("没有jid就不给你修改！");
			return;
		}
		String[] args = { jid };
		ContentValues values = new ContentValues();
		values.put("_lastRecord", lastContact);
		if (db.update(DATING_RECORD, values, "_jid=?", args) != -1) {
			ALLog.d(lastContact + "更新约会列表成功");
		}
	}

	/**
	 * 设置指定约会记录的在线状态
	 * 
	 * @param jid
	 *            ： 要修改的约会记录jid
	 * @param status
	 *            ： 0 离线, 1 在线, 2 忙碌, 3 离开
	 */
	public void setDateRecordStatus(String jid, int status) {
		if (TextUtils.isEmpty(jid)) {
			ALLog.d("没有jid就不给你修改！");
			return;
		}

		String[] args = { jid };
		ContentValues values = new ContentValues();
		values.put("_status", status);

		db.update(DATING_RECORD, values, "_jid=?", args);
	}

	/**
	 * 设置约会记录最后一条消息的时间
	 * 
	 * @param jid
	 *            ： 要修改的约会记录jid
	 * @param msgTime
	 *            ： 最后一条消息的时间; 没有消息就设为null
	 */
	public void setDateRecordMsgTime(String jid, Date msgTime) {
		if (TextUtils.isEmpty(jid)) {
			ALLog.d("没有jid就不给你修改！");
			return;
		}

		String[] args = { jid };
		ContentValues values = new ContentValues();

		if (msgTime != null) {
			ALLog.d("居然有最后一条消息的时间");
			values.put("_lastMsgTime", msgTime.getTime());
			values.put("_isExistMsg", 1);
		} else {
			ALLog.d("没时间");
			values.put("_lastMsgTime", 0);
			values.put("_isExistMsg", 0);
		}

		db.update(DATING_RECORD, values, "_jid=?", args);
	}

	/**
	 * 设置约会记录最后一条消息的时间
	 * 
	 * @param jid
	 *            ： 要修改的约会记录jid
	 * @param msgTime
	 *            ： 最后一条消息的时间; 没有消息就设为null
	 */
	public void setDateRecordLastMsg(String jid, String msg) {
		if (TextUtils.isEmpty(jid)) {
			ALLog.d("没有jid就不给你修改！");
			return;
		}

		String[] args = { jid };
		ContentValues values = new ContentValues();
		values.put("_lastMsg", msg);

		db.update(DATING_RECORD, values, "_jid=?", args);
	}

	/**
	 * 设置约会记录是否有未读消息
	 * 
	 * @param jid
	 *            ：要修改的约会记录jid
	 * @param isUnread
	 *            ：未读状态
	 */
	public void setDateRecordMsgStatus(String jid, boolean isUnread) {
		if (TextUtils.isEmpty(jid)) {
			ALLog.d("没有jid就不给你修改！");
			return;
		}

		String[] args = { jid };
		ContentValues values = new ContentValues();
		values.put("_isExistUnreadMsg", isUnread ? 1 : 0);

		db.update(DATING_RECORD, values, "_jid=?", args);
	}

	/**
	 * 设置约会记录的头像
	 * 
	 * @param jid
	 *            ： 要修改的约会记录jid
	 * @param url
	 *            ：头像url
	 */
	public void setDateRecordAvatar(String jid, String url) {
		if (TextUtils.isEmpty(jid)) {
			ALLog.d("没有jid就不给你修改！");
			return;
		}

		String[] args = { jid };
		ContentValues values = new ContentValues();

		if (!TextUtils.isEmpty(url)) {
			ALLog.d("居然有头像");
			values.put("_imageFileid", url);
		} else {
			ALLog.d("没头像");
			values.put("_imageFileid", "");
		}

		db.update(DATING_RECORD, values, "_jid=?", args);
	}

	/**
	 * 设置约会记录的头像
	 * 
	 * @param jid
	 *            ： 要修改的约会记录jid
	 * @param url
	 *            ：头像url
	 */
	public void setDateRecordNick(String jid, String nick) {
		if (TextUtils.isEmpty(jid)) {
			ALLog.d("没有jid就不给你修改！");
			return;
		}

		String[] args = { jid };
		ContentValues values = new ContentValues();

		if (!TextUtils.isEmpty(nick)) {
			ALLog.d("重新设置昵称" + nick);
			values.put("_nick", nick);
			db.update(DATING_RECORD, values, "_jid=?", args);
		}
	}

	public void setDateRecordDistanceFromMe(String jid, String distance) {
		if (TextUtils.isEmpty(jid)) {
			ALLog.d("没有jid就不给你修改！");
			return;
		}

		String[] args = { jid };
		ContentValues values = new ContentValues();

		if (!TextUtils.isEmpty(distance)) {
			ALLog.d("重新设置距离" + distance);
			values.put("_distance", distance);
			db.update(DATING_RECORD, values, "_distance=?", args);
		}
	}

	/**
	 * 设置约会记录的时长
	 * 
	 * @param jid
	 *            ： 要修改的约会记录jid
	 * @param time
	 *            ： 时长
	 */
	public void setDateRecordDuration(String jid, String time) {
		if (TextUtils.isEmpty(jid)) {
			ALLog.d("没有jid就不给你修改！");
			return;
		}

		String[] args = { jid };
		ContentValues values = new ContentValues();

		if (TextUtils.isEmpty(time)) {
			ALLog.d("居然有时长");
			values.put("_duration", time);
		} else {
			ALLog.d("没时长");
			values.put("_duration", "");
		}

		db.update(DATING_RECORD, values, "_jid=?", args);
	}

	public void updateDateRecordCustomScene(String jid, String customScene) {
		if (TextUtils.isEmpty(jid)) {
			ALLog.d("没有jid就不给你修改！");
			return;
		}

		String[] args = { jid };
		ContentValues values = new ContentValues();
		values.put("_customScene", customScene);

		db.update(DATING_RECORD, values, "_jid=?", args);
		ALLog.d("更改约会自定义背景");
	}

	public void updateDateRecordResponsed(String jid) {
		if (TextUtils.isEmpty(jid)) {
			ALLog.d("没有jid就不给你修改！");
			return;
		}

		String[] args = { jid };
		ContentValues values = new ContentValues();
		values.put("_responsed", 1);

		db.update(DATING_RECORD, values, "_jid=?", args);
		ALLog.d("修改绣球约会记录中的回应状态");
	}

	/**
	 * 判断约会记录的头像是否一致
	 * 
	 * @param jid
	 *            ： 约会记录jid
	 * @param url
	 *            ： 头像
	 * @return : true一致; false不一致
	 */
	public boolean isTheSameDateRecordAvatar(String jid, String url) {
		if (TextUtils.isEmpty(jid)) {
			ALLog.d("你确定没jid可以查到记录？？");
			return false;
		}

		boolean isSame = false;

		DateRecords date = getDateRecordByJid(jid);

		if (TextUtils.isEmpty(date.getImageFileId()) && TextUtils.isEmpty(url)) {
			isSame = true;
		} else {
			String original = date.getImageFileId();
			if (original == null)
				original = "";

			isSame = original.equals(url);
		}

		return isSame;
	}

	/**
	 * 插入多个@的人
	 * 
	 * @param users
	 */
	public void insertLastedUsers(ArrayList<User> users) {
		if (users != null && users.size() > 0) {
			for (User user : users) {
				insertLastedUser(user);
			}
		}
	}

	/**
	 * 添加最近@的人信息
	 * 
	 * @param mTweet
	 */
	public void insertLastedUser(User mUser) {
		if (mUser == null) {
			ALLog.d("你妹的！传个空的对象给我，存个毛线啊！");
			return;
		}
		deleteLastedUserByJid(mUser.getJid());
		ContentValues contentValues = new ContentValues();
		contentValues.put("_jid", mUser.getJid());
		contentValues.put("_nick", mUser.getNick());
		contentValues.put("_imagefileid", mUser.getImageFileId());
		contentValues.put("_addtime", System.currentTimeMillis());
		if (db.insert(MY_PLAZA_LASTED_ADD_USER, "", contentValues) == -1) {
			ALLog.d("保存最近@的人 失败");
			return;
		}

		ALLog.d("保存最近@的人 成功");

	}

	/**
	 * 根据jid删除最近@的人
	 * 
	 * @param jid
	 */
	public void deleteLastedUserByJid(String jid) {
		db.delete(MY_PLAZA_LASTED_ADD_USER, " _jid=?", new String[] { jid });
	}

	/**
	 * 获取数据库中的所有最近@的人
	 * 
	 * @return
	 */
	public ArrayList<User> getAllLastedUser() {
		ArrayList<User> list = new ArrayList<User>();
		User mUser = null;
		Cursor c = null;
		try {
			c = db.rawQuery("SELECT * FROM " + MY_PLAZA_LASTED_ADD_USER
					+ " order by _addtime desc", null);
			if (c != null && c.getCount() > 0) {
				while (c.moveToNext()) {
					String jid = c.getString(c.getColumnIndex("_jid"));
					String nick = c.getString(c.getColumnIndex("_nick"));
					String imagefileid = c.getString(c
							.getColumnIndex("_imagefileid"));
					mUser = new User();
					mUser.setJid(jid);
					mUser.setNick(nick);
					mUser.setImageFileId(imagefileid);
					list.add(mUser);
				}
			}
		} catch (Throwable t) {
			ALLog.d(t.toString());
		} finally {
			if (c != null) {
				try {
					c.close();
				} catch (Exception e) {
				}
			}
		}

		ALLog.d("一共有" + list.size() + "个的最近@的人");
		return list;
	}

	/**
	 * 删除道具信息列表数据
	 * 
	 * @return
	 */
	public void deleteAllPropsMallList() {

		db.delete(MY_PROPS_MAILL_LIST, null, null);
	}

	/**
	 * 保存道具信息
	 * 
	 * @param p
	 */
	public void savePropsMallList(final ArrayList<Prop> plist) {
		// 先清空数据
		deleteAllPropsMallList();

		if (plist == null || plist.size() < 1) {

			ALLog.d("保存道具信息 传入的list是的空的没有东西.");
			return;
		}

		/*
		 * new Thread(){
		 * 
		 * @Override public void run() {
		 */
		for (Prop p : plist) {

			ContentValues cv = new ContentValues();
			cv.put("_props", p.getProp());
			cv.put("_propsname", p.getPropName());
			cv.put("_propstype", p.getPropType());
			cv.put("_propstypename", p.getPropTypeName());
			cv.put("_fileid", p.getPropFileId());
			cv.put("_propslevel", p.getPropLevel() + "");
			cv.put("_desc", p.getPropDesc());
			cv.put("_propindex", p.getPropIndex() + "");
			cv.put("_propsindex", p.getPropsIndex() + "");

			if (db.insert(MY_PROPS_MAILL_LIST, "", cv) == -1) {

				ALLog.d(p.getPropName() + "保存道具列表失败");
			} else {
				ALLog.d(p.getPropName() + "道具保存成功");
			}
		}
		/*
		 * } }.start();
		 */

		ALLog.d("保存道具列表成功");
	}

	/*
	 * private synchronized void inertdata(ContentValues cv,Prop p) {
	 * if(db.insert(MY_PROPS_MAILL_LIST, "", cv) == -1){
	 * 
	 * ALLog.d( p.getPropName()+"保存道具列表失败"); }else { ALLog.d(
	 * p.getPropName()+"道具保存成功"); } }
	 */

	/**
	 * 获取道具类型和道具名称
	 * 
	 * @return
	 */
	public ArrayList<Prop> getAllPropTypeorTypeName() {

		ArrayList<Prop> list = new ArrayList<Prop>();

		Cursor c = null;
		try {
			c = db.rawQuery("SELECT _propstype,_propstypename FROM "
					+ MY_PROPS_MAILL_LIST
					+ " GROUP BY _propstype order by _propsindex asc", null);
			if (c != null && c.getCount() > 0) {
				while (c.moveToNext()) {
					Prop p = new Prop();
					p.setPropType(c.getString(c.getColumnIndex("_propstype")));
					p.setPropTypeName(c.getString(c
							.getColumnIndex("_propstypename")));

					list.add(p);
				}
			}
		} catch (Throwable t) {
			ALLog.d(t.toString());
		} finally {
			if (c != null) {
				try {
					c.close();
				} catch (Exception e) {
				}
			}
		}

		ALLog.d("一共有" + list.size() + "道具类型数量");

		return list;
	}

	/**
	 * 根据设置的条件查找道具列表
	 * 
	 * @param where
	 * @param arg
	 * @return
	 */
	public ArrayList<Prop> getPropListByArgs(String where, String[] arg) {
		ArrayList<Prop> list = new ArrayList<Prop>();

		Cursor c = null;
		try {
			c = db.rawQuery("SELECT * FROM " + MY_PROPS_MAILL_LIST + " "
					+ where, arg);
			if (c != null && c.getCount() > 0) {
				while (c.moveToNext()) {
					Prop p = new Prop();

					p.setProp(c.getString(c.getColumnIndex("_props")));
					p.setPropName(c.getString(c.getColumnIndex("_propsname")));
					p.setPropType(c.getString(c.getColumnIndex("_propstype")));
					p.setPropTypeName(c.getString(c
							.getColumnIndex("_propstypename")));
					p.setPropFileId(c.getString(c.getColumnIndex("_fileid")));
					int level = 0;
					String leveltr = c.getString(c
							.getColumnIndex("_propslevel"));
					if (leveltr != null && leveltr.length() > 0
							&& leveltr.matches("\\d*")) {
						level = Integer.parseInt(leveltr);
					}
					p.setPropLevel(level);
					p.setPropDesc(c.getString(c.getColumnIndex("_desc")));
					int propindex = 0;
					String propindexstr = c.getString(c
							.getColumnIndex("_propindex"));
					if (propindexstr != null && propindexstr.length() > 0
							&& propindexstr.matches("\\d*")) {
						propindex = Integer.parseInt(propindexstr);
					}
					p.setPropIndex(propindex);

					int propsindex = 0;
					String propsindexstr = c.getString(c
							.getColumnIndex("_propsindex"));
					if (propsindexstr != null && propsindexstr.length() > 0
							&& propsindexstr.matches("\\d*")) {
						propsindex = Integer.parseInt(propsindexstr);
					}
					p.setPropsIndex(propsindex);

					list.add(p);
				}
			}
		} catch (Throwable t) {
			ALLog.d(t.toString());
		} finally {
			if (c != null) {
				try {
					c.close();
				} catch (Exception e) {
				}
			}
		}

		ALLog.d("一共有 getPropListByArgs " + list.size() + "道具类型数量");

		return list;
	}

	/**
	 * 根据prop查询道具信息
	 * 
	 * @param prop
	 * @return
	 */
	public Prop getPropByProp(String prop) {
		ArrayList<Prop> plist = new ArrayList<Prop>();
		plist.clear();

		ArrayList<Prop> list = getPropListByArgs(" where _props =?",
				new String[] { prop });

		plist.addAll(list);

		if (plist != null && plist.size() > 0) {

			return plist.get(0);
		} else {
			ALLog.d("getPropByProp 尼玛根据prop查不到道具信息.");
			return null;
		}
	}

	/**
	 * 根据prop查询道具信息
	 * 
	 * @param prop
	 * @return
	 */
	public Prop getPropByPropTypeAndPropLevel(String propType, String propLevel) {
		ArrayList<Prop> plist = new ArrayList<Prop>();
		plist.clear();

		ArrayList<Prop> list = getPropListByArgs(
				" where _propstype = ? and _propslevel = ?", new String[] {
						propType, propLevel });

		plist.addAll(list);

		if (plist != null && plist.size() > 0) {

			return plist.get(0);
		} else {
			ALLog.d("getPropByPropTypeAndPropLevel 尼玛根据prop查不到道具信息.");
			return null;
		}
	}

	/**
	 * 根据prop查询道具信息
	 * 
	 * @param prop
	 * @return
	 */
	public Prop getPropByPropType(String propType) {
		ArrayList<Prop> plist = new ArrayList<Prop>();
		plist.clear();

		ArrayList<Prop> list = getPropListByArgs(" where _propstype = ? ",
				new String[] { propType });

		plist.addAll(list);

		if (plist != null && plist.size() > 0) {

			return plist.get(0);
		} else {
			ALLog.d("getPropByPropType 尼玛根据prop查不到道具信息.");
			return null;
		}
	}

	/**
	 * 根据prop查询道具信息
	 * 
	 * @param prop
	 * @return
	 */
	public Prop getPropsByPropType(String propType) {
		ArrayList<Prop> plist = new ArrayList<Prop>();
		plist.clear();

		ArrayList<Prop> list = getPropListByArgs(" where _props = ? ",
				new String[] { propType });

		plist.addAll(list);

		if (plist != null && plist.size() > 0) {

			return plist.get(0);
		} else {
			ALLog.d("getPropByPropType 尼玛根据prop查不到道具信息.");
			return null;
		}
	}

	/**
	 * 获取道具商城列表
	 * 
	 * @return
	 */
	public ArrayList<Props> getAllPropsList() {

		ArrayList<Props> propslist = new ArrayList<Props>();

		ArrayList<Prop> propTypelist = getAllPropTypeorTypeName();

		Props ps = null;

		if (propTypelist != null && propTypelist.size() > 0) {

			for (Prop p : propTypelist) {

				ps = new Props();
				ps.setPropsName(p.getPropTypeName());
				ps.setPropsType(p.getPropType());

				ArrayList<Prop> plist = new ArrayList<Prop>();
				plist = getPropListByArgs(
						"where _propstype =? order by _propindex",
						new String[] { p.getPropType() });

				ps.setPropitems(plist);

				propslist.add(ps);

			}

		} else {
			ALLog.d("getAllPropsList prop 类型信息集合木有数据.");
		}

		ALLog.d("getAllPropsList propslist 共有" + propslist.size() + "条数据");
		return propslist;

	}

	public int loadNewCount(String key) {
		if (TextUtils.isEmpty(key)) {
			return 0;
		}

		int count = 0;

		String[] arg = { key };
		Cursor c = null;
		String sql = String.format("SELECT _count FROM %s where _key=?",
				NEW_COUNT_TABLE);

		try {
			c = db.rawQuery(sql, arg);

			if (null != c) {
				if (c.moveToNext()) {
					count = c.getInt((c.getColumnIndex("_count")));
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != c) {

				try {
					c.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		return count;
	}

	public void saveNewCount(String key, int count) {
		if (TextUtils.isEmpty(key)) {
			return;
		}

		deleteNewCount(key);

		ContentValues values = new ContentValues();
		values.put("_key", key);
		values.put("_count", count);

		try {
			db.insert(NEW_COUNT_TABLE, null, values);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void deleteNewCount(String key) {
		if (TextUtils.isEmpty(key)) {
			return;
		}

		String arg[] = { key };
		try {
			db.delete(NEW_COUNT_TABLE, "(_key=?)", arg);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/************ 我的收藏 *********/
	/**
	 * 更新信息表，将原来的数据清除
	 */
	public void updateFavoriteForMyList(ArrayList<User> users) {
		deleteAllFavoriteList();
		db.beginTransaction();// 为处理大批量
		for (int i = 0; i < users.size(); i++) {
			User mUser = users.get(i);
			insertFavoriteUser(mUser);
		}
		db.setTransactionSuccessful();
		db.endTransaction();
	}

	/**
	 * 添加我的收藏列表
	 * 
	 * @param mTweet
	 */
	public void insertFavoriteUser(User mUser) {
		if (mUser == null) {
			ALLog.d("你妹的！传个空的对象给我，存个毛线啊！");
			return;
		}

		ContentValues contentValues = new ContentValues();
		contentValues.put("_jid", mUser.getJid());
		contentValues.put("_nick", mUser.getNick());
		contentValues.put("_sex", mUser.getSex());
		contentValues.put("_age", mUser.getBirtyday());
		contentValues.put("_sig", mUser.getSignature());
		contentValues.put("_avatar", mUser.getImageFileId());
		contentValues.put("_viplevel", mUser.getViplevel());
		contentValues.put("_halloffame", mUser.getHalloffame());
		contentValues.put("_starState", mUser.getStarState());
		ALLog.d("名字是啥" + mUser.getNick());
		if (mUser.getSpecial_focus().equals("1")) {
			contentValues.put("_namespell",
					"☆" + PinYinUtil.getStrFirstSpell(mUser.getNick()));
		} else {
			contentValues.put("_namespell",
					PinYinUtil.getStrFirstSpell(mUser.getNick()));
		}
		contentValues.put("_isfriend", mUser.getIsfriend());
		contentValues.put("_isspecial", mUser.getSpecial_focus());
		contentValues.put("_subscription", mUser.getSubscription());
		contentValues.put("_subendtime", mUser.getEndsubscriptionTime());
		contentValues.put("_starState", mUser.getStarState());
		if (db.insert(MY_FAVORITE_FORMY, "", contentValues) == -1) {
			ALLog.d("保存我的收藏列表 失败");
			return;
		}

		ALLog.d("保存我的收藏列表 成功");

	}

	public void updateFavorteUserById(String jid) {
		String[] arg = { jid };
		Cursor c = db.rawQuery("SELECT * FROM " + MY_FAVORITE_FORMY
				+ " WHERE _jid=?", arg);
		if (null != c) {
			ContentValues values = new ContentValues();
			values.put("_isfriend", "false");
			db.update(MY_FAVORITE_FORMY, values, "_jid=?", arg);
		}
	}

	/**
	 * 更新我的收藏列表
	 * 
	 * @param mTweet
	 */
	public void updateFavoriteUser(User mUser) {
		if (mUser == null) {
			ALLog.d("你妹的！传个空的对象给我，更新个毛线啊！");
			return;
		}
		String fileid = mUser.getImageFileId();
		;
		if (mUser.getPhotos().size() > 0) {
			fileid = mUser.getPhotos().get(0).getThumbnailFileid();
		}
		String birth = mUser.getBirtyday();
		if (!TextUtils.isEmpty(birth) && birth.indexOf("-") != -1) {
			birth = birth.substring(0, birth.indexOf("-"));
			Calendar now = Calendar.getInstance();
			birth = (now.get(Calendar.YEAR) - Integer.parseInt(birth)) + "";
		}
		if (getFavoriteForMyByJid(mUser.getJid()) != null) {
			String[] arg = { mUser.getJid() };
			ContentValues contentValues = new ContentValues();
			contentValues.put("_nick", mUser.getNick());
			contentValues.put("_sex", mUser.getSex());
			contentValues.put("_age", birth);
			contentValues.put("_sig", mUser.getSignature());
			contentValues.put("_avatar", fileid);
			contentValues.put("_viplevel", mUser.getViplevel());
			contentValues.put("_halloffame", mUser.getHalloffame());
			if (mUser.getSpecial_focus().equals("1")) {
				contentValues.put("_namespell",
						"☆" + PinYinUtil.getStrFirstSpell(mUser.getNick()));
			} else {
				contentValues.put("_namespell",
						PinYinUtil.getStrFirstSpell(mUser.getNick()));
			}
			contentValues.put("_isfriend", mUser.getIsfriend());
			contentValues.put("_isspecial", mUser.getSpecial_focus());
			contentValues.put("_subscription", mUser.getSubscription());
			contentValues.put("_subendtime", mUser.getEndsubscriptionTime());
			contentValues.put("_starState", mUser.getStarState());

			if (db.update(MY_FAVORITE_FORMY, contentValues, "_jid=?", arg) == -1) {
				ALLog.d("更新我的收藏列表 失败");
				return;
			}
			ALLog.d("更新我的收藏列表 成功");
		} else {
			ALLog.d(mUser.getJid() + "没有被收藏，更新个毛线");
		}
	}

	/**
	 * 根据jid删除我的收藏
	 * 
	 * @param jid
	 */
	public void deleteFavoriteListById(String jid) {
		db.delete(MY_FAVORITE_FORMY, " _jid=?", new String[] { jid });
	}

	/**
	 * 删除所有的我的收藏数据
	 */
	public void deleteAllFavoriteList() {
		db.delete(MY_FAVORITE_FORMY, null, null);
	}

	public User getFavoriteForMyByJid(String jid) {
		User mUser = null;
		String[] args = new String[] { jid };
		Cursor c = null;
		try {
			c = db.rawQuery("SELECT * FROM " + MY_FAVORITE_FORMY
					+ " WHERE _jid=?", args);
			if (c != null && c.getCount() > 0) {
				if (c.moveToNext()) {
					String nick = c.getString(c.getColumnIndex("_nick"));
					String sex = c.getString(c.getColumnIndex("_sex"));
					String age = c.getString(c.getColumnIndex("_age"));
					String sig = c.getString(c.getColumnIndex("_sig"));
					String avatar = c.getString(c.getColumnIndex("_avatar"));
					int viplevel = c.getInt(c.getColumnIndex("_viplevel"));

					String halloffame = c.getString(c
							.getColumnIndex("_halloffame"));
					String spellname = c.getString(c
							.getColumnIndex("_namespell"));
					String isfriend = c
							.getString(c.getColumnIndex("_isfriend"));
					String isspecial = c.getString(c
							.getColumnIndex("_isspecial"));
					String subscription = c.getString(c
							.getColumnIndex("_subscription"));
					String subendtime = c.getString(c
							.getColumnIndex("_subendtime"));

					int starState = c.getInt(c.getColumnIndex("_starState"));

					mUser = new User();
					mUser.setJid(jid);
					mUser.setNick(nick);
					mUser.setSex(sex);
					mUser.setBirthday(age);
					mUser.setSignature(sig);
					mUser.setImageFileId(avatar);
					mUser.setViplevel(viplevel);
					mUser.setHalloffame(halloffame);
					mUser.setSpellName(spellname);
					mUser.setIsfriend(isfriend);
					mUser.setSpecial_focus(isspecial);
					mUser.setSubscription(subscription);
					mUser.setEndsubscriptionTime(subendtime);
					mUser.setStarState(starState);
				}
			}
		} catch (Throwable t) {
			ALLog.d(t.toString());
		} finally {
			if (c != null) {
				try {
					c.close();
				} catch (Exception e) {
				}
			}
		}
		return mUser;
	}

	/**
	 * 获取数据库中的我的收藏列表
	 * 
	 * @return
	 */
	public ArrayList<User> getAllFavoriteForMyList(int offset) {
		ArrayList<User> list = new ArrayList<User>();
		User mUser = null;
		Cursor c = null;
		try {
			c = db.rawQuery("SELECT * FROM " + MY_FAVORITE_FORMY
					+ " order by _isspecial desc, _namespell LIMIT "
					+ (offset + 1) * DEFAULT_PAGE_COUNT, null);
			if (c != null && c.getCount() > 0) {
				while (c.moveToNext()) {
					String jid = c.getString(c.getColumnIndex("_jid"));
					String nick = c.getString(c.getColumnIndex("_nick"));
					String sex = c.getString(c.getColumnIndex("_sex"));
					String age = c.getString(c.getColumnIndex("_age"));
					String sig = c.getString(c.getColumnIndex("_sig"));
					String avatar = c.getString(c.getColumnIndex("_avatar"));
					String halloffame = c.getString(c
							.getColumnIndex("_halloffame"));
					int viplevel = c.getInt(c.getColumnIndex("_viplevel"));
					String spellname = c.getString(c
							.getColumnIndex("_namespell"));
					String isfriend = c
							.getString(c.getColumnIndex("_isfriend"));
					String isspecial = c.getString(c
							.getColumnIndex("_isspecial"));
					String subscription = c.getString(c
							.getColumnIndex("_subscription"));
					String subendtime = c.getString(c
							.getColumnIndex("_subendtime"));

					int starState = c.getInt(c.getColumnIndex("_starState"));

					mUser = new User();
					mUser.setStarState(starState);
					mUser.setJid(jid);
					mUser.setNick(nick);
					mUser.setSex(sex);
					mUser.setBirthday(age);
					mUser.setSignature(sig);
					mUser.setImageFileId(avatar);
					mUser.setViplevel(viplevel);
					mUser.setHalloffame(halloffame);
					mUser.setSpellName(spellname);
					mUser.setIsfriend(isfriend);
					mUser.setSpecial_focus(isspecial);
					mUser.setSubscription(subscription);
					mUser.setEndsubscriptionTime(subendtime);
					list.add(mUser);

				}
			}
		} catch (Throwable t) {
			ALLog.d(t.toString());
		} finally {
			if (c != null) {
				try {
					c.close();
				} catch (Exception e) {
				}
			}
		}

		ALLog.d("一共有" + list.size() + "收藏列表");
		return list;
	}

	/**
	 * 搜索数据库中的我的收藏列表
	 * 
	 * @return
	 */
	public ArrayList<User> SearchFavoriteForMyList(String keyword) {
		ArrayList<User> list = new ArrayList<User>();
		User mUser = null;
		Cursor c = null;
		try {
			c = db.rawQuery("SELECT * FROM " + MY_FAVORITE_FORMY
					+ " WHERE _nick like '%" + keyword + "%'   ", null);
			if (c != null && c.getCount() > 0) {
				while (c.moveToNext()) {
					String jid = c.getString(c.getColumnIndex("_jid"));
					String nick = c.getString(c.getColumnIndex("_nick"));
					String sex = c.getString(c.getColumnIndex("_sex"));
					String age = c.getString(c.getColumnIndex("_age"));
					String sig = c.getString(c.getColumnIndex("_sig"));
					String avatar = c.getString(c.getColumnIndex("_avatar"));
					int viplevel = c.getInt(c.getColumnIndex("_viplevel"));
					String halloffame = c.getString(c
							.getColumnIndex("_halloffame"));
					String isspecial = c.getString(c
							.getColumnIndex("_isspecial"));
					String spellname = c.getString(c
							.getColumnIndex("_namespell"));
					String isfriend = c
							.getString(c.getColumnIndex("_isfriend"));
					String subscription = c.getString(c
							.getColumnIndex("_subscription"));
					String subendtime = c.getString(c
							.getColumnIndex("_subendtime"));

					int starState = c.getInt(c.getColumnIndex("_starState"));

					mUser = new User();
					mUser.setStarState(starState);
					mUser.setJid(jid);
					mUser.setNick(nick);
					mUser.setSex(sex);
					mUser.setBirthday(age);
					mUser.setSignature(sig);
					mUser.setImageFileId(avatar);
					mUser.setViplevel(viplevel);
					mUser.setHalloffame(halloffame);
					mUser.setSpellName(spellname);
					mUser.setIsfriend(isfriend);
					mUser.setSubscription(subscription);
					mUser.setSpecial_focus(isspecial);
					mUser.setEndsubscriptionTime(subendtime);
					list.add(mUser);
				}
			}
		} catch (Throwable t) {
			ALLog.d(t.toString());
		} finally {
			if (c != null) {
				try {
					c.close();
				} catch (Exception e) {
				}
			}
		}

		ALLog.d("一共有" + list.size() + "搜索结果");
		return list;
	}

	/**
	 * 获取用户收藏总数
	 * 
	 * @return count
	 */
	public int getFavotiteForMyCount() {
		int count = 0;
		Cursor c = null;

		String sql = "select count(*) as counts from  " + MY_FAVORITE_FORMY;
		try {
			c = db.rawQuery(sql, null);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (c != null && c.getCount() > 0) {

			while (c.moveToNext()) {
				count = c.getInt(c.getColumnIndex("counts"));
			}
		}

		if (c != null) {
			c.close();
		}

		ALLog.d("该用户收藏的总数 count:" + count);
		return count;
	}

	/**
	 * 更新粉丝列表表，将原来的数据清除
	 */
	public void updateFavoriteToMyList(ArrayList<User> users) {
		ALLog.d("更新了");
		deleteAllFavoriteToList();
		db.beginTransaction();// 为处理大批量
		for (int i = 0; i < users.size(); i++) {
			User mUser = users.get(i);
			insertFavoriteToUser(mUser, true);
		}
		db.setTransactionSuccessful();
		db.endTransaction();
	}

	public User getFavoriteForToByJid(String jid) {
		User mUser = null;
		String[] args = new String[] { jid };
		Cursor c = null;
		try {
			c = db.rawQuery("SELECT * FROM " + MY_FAVORITE_TOMY
					+ " WHERE _jid=?", args);
			if (c != null && c.getCount() > 0) {
				if (c.moveToNext()) {
					String nick = c.getString(c.getColumnIndex("_nick"));
					String sex = c.getString(c.getColumnIndex("_sex"));
					String age = c.getString(c.getColumnIndex("_age"));
					String sig = c.getString(c.getColumnIndex("_sig"));
					String avatar = c.getString(c.getColumnIndex("_avatar"));
					String time = c.getString(c.getColumnIndex("_time"));
					int viplevel = c.getInt(c.getColumnIndex("_viplevel"));
					String halloffame = c.getString(c
							.getColumnIndex("_halloffame"));
					String spellname = c.getString(c
							.getColumnIndex("_namespell"));
					String isfriend = c
							.getString(c.getColumnIndex("_isfriend"));
					String subscription = c.getString(c
							.getColumnIndex("_subscription"));
					int starState = c.getInt(c.getColumnIndex("_starState"));

					mUser = new User();
					mUser.setStarState(starState);
					mUser.setJid(jid);
					mUser.setNick(nick);
					mUser.setSex(sex);
					mUser.setBirthday(age);
					mUser.setSignature(sig);
					mUser.setImageFileId(avatar);
					mUser.setFavorites_time(time);
					mUser.setViplevel(viplevel);
					mUser.setHalloffame(halloffame);
					mUser.setSpellName(spellname);
					mUser.setIsfriend(isfriend);
					mUser.setSubscription(subscription);
				}
			}
		} catch (Throwable t) {
			ALLog.d(t.toString());
		} finally {
			if (c != null) {
				try {
					c.close();
				} catch (Exception e) {
				}
			}
		}
		return mUser;
	}

	/**
	 * 添加我的粉丝列表
	 * 
	 * @param mTweet
	 */
	public void insertFavoriteToUser(User mUser, boolean isClear) {
		if (mUser == null) {
			ALLog.d("你妹的！传个空的对象给我，存个毛线啊！");
			return;
		}
		if (isClear || getFavoriteForToByJid(mUser.getJid()) == null) {
			ContentValues contentValues = new ContentValues();
			contentValues.put("_jid", mUser.getJid());
			contentValues.put("_nick", mUser.getNick());
			contentValues.put("_sex", mUser.getSex());
			contentValues.put("_age", mUser.getBirtyday());
			contentValues.put("_sig", mUser.getSignature());
			contentValues.put("_avatar", mUser.getImageFileId());
			contentValues.put("_time", mUser.getFavorites_time());
			contentValues.put("_viplevel", mUser.getViplevel());
			contentValues.put("_halloffame", mUser.getHalloffame());
			contentValues.put("_namespell",
					PinYinUtil.getStrFirstSpell(mUser.getNick()));
			contentValues.put("_isfriend", mUser.getIsfriend());
			contentValues.put("_subscription", mUser.getSubscription());
			contentValues.put("_starState", mUser.getStarState());

			if (db.insert(MY_FAVORITE_TOMY, "", contentValues) == -1) {
				ALLog.d("保存我的粉丝列表 失败");
				return;
			}
			ALLog.d("保存我的粉丝列表 成功");
		} else {
			String[] arg = { mUser.getJid() };
			ContentValues contentValues = new ContentValues();
			contentValues.put("_nick", mUser.getNick());
			contentValues.put("_sex", mUser.getSex());
			contentValues.put("_age", mUser.getBirtyday());
			contentValues.put("_sig", mUser.getSignature());
			contentValues.put("_avatar", mUser.getImageFileId());
			contentValues.put("_viplevel", mUser.getViplevel());
			contentValues.put("_halloffame", mUser.getHalloffame());
			contentValues.put("_namespell",
					PinYinUtil.getStrFirstSpell(mUser.getNick()));
			contentValues.put("_isfriend", mUser.getIsfriend());
			contentValues.put("_subscription", mUser.getSubscription());
			contentValues.put("_starState", mUser.getStarState());
			if (db.update(MY_FAVORITE_TOMY, contentValues, "_jid=?", arg) == -1) {
				ALLog.d("更新我的粉丝列表 失败");
				return;
			}
			ALLog.d("更新我的粉丝列表 成功");
		}
	}

	/**
	 * 根据id更新我的粉丝关注状态
	 */
	public void updateFavoriteToUserById(String jid, String isFriend) {
		if (!TextUtils.isEmpty(jid)) {
			String[] arg = { jid };
			ContentValues contentValues = new ContentValues();
			contentValues.put("_isfriend", isFriend);
			if (db.update(MY_FAVORITE_TOMY, contentValues, "_jid=?", arg) == -1) {
				ALLog.d("更新我的粉丝列表 失败");
				return;
			}
		}
	}

	/**
	 * 根据id更新我的收藏订阅状态
	 */
	public void updateFavoriteToMe_sub(String jid, String _subscription) {
		if (!TextUtils.isEmpty(jid)) {
			String[] arg = { jid };
			ContentValues contentValues = new ContentValues();
			contentValues.put("_subscription", _subscription);
			if (db.update(MY_FAVORITE_FORMY, contentValues, "_jid=?", arg) == -1) {
				ALLog.d("更新我的粉丝列表 失败");
				return;
			}
		}
	}

	/**
	 * 根据id更新我的收藏订阅状态
	 */
	public void updateFavoriteToUser_sub(String jid, String _subscription) {
		if (!TextUtils.isEmpty(jid)) {
			String[] arg = { jid };
			ContentValues contentValues = new ContentValues();
			contentValues.put("_subscription", _subscription);
			if (db.update(MY_FAVORITE_TOMY, contentValues, "_jid=?", arg) == -1) {
				ALLog.d("更新我的粉丝列表 失败");
				return;
			}
		}
	}

	/**
	 * 更新我的收藏列表
	 * 
	 * @param mTweet
	 */
	public void updateFavoriteToUser(User mUser) {
		if (mUser == null) {
			ALLog.d("你妹的！传个空的对象给我，更新个毛线啊！");
			return;
		}
		String fileid = mUser.getImageFileId();
		if (mUser.getPhotos().size() > 0) {
			fileid = mUser.getPhotos().get(0).getThumbnailFileid();
		}
		String birth = mUser.getBirtyday();
		if (!TextUtils.isEmpty(birth) && birth.indexOf("-") != -1) {
			birth = birth.substring(0, birth.indexOf("-"));
			Calendar now = Calendar.getInstance();
			birth = (now.get(Calendar.YEAR) - Integer.parseInt(birth)) + "";
		}
		if (getFavoriteForToByJid(mUser.getJid()) != null) {
			String[] arg = { mUser.getJid() };
			ContentValues contentValues = new ContentValues();
			contentValues.put("_nick", mUser.getNick());
			contentValues.put("_sex", mUser.getSex());
			contentValues.put("_age", birth);
			contentValues.put("_sig", mUser.getSignature());
			contentValues.put("_avatar", fileid);
			contentValues.put("_viplevel", mUser.getViplevel());
			contentValues.put("_halloffame", mUser.getHalloffame());
			contentValues.put("_namespell",
					PinYinUtil.getStrFirstSpell(mUser.getNick()));
			contentValues.put("_isfriend", mUser.getIsfriend());
			contentValues.put("_subscription", mUser.getSubscription());
			contentValues.put("_starState", mUser.getStarState());
			if (db.update(MY_FAVORITE_TOMY, contentValues, "_jid=?", arg) == -1) {
				ALLog.d("更新我的粉丝列表 失败");
				return;
			}
			ALLog.d("更新我的粉丝列表 成功");
		} else {
			ALLog.d(mUser.getJid() + "不是粉丝，更新个毛线");
		}
	}

	/**
	 * 根据jid删除我的粉丝
	 * 
	 * @param jid
	 */
	public void deleteFavoriteToListById(String jid) {
		db.delete(MY_FAVORITE_TOMY, " _jid=?", new String[] { jid });
	}

	/**
	 * 删除所有的我的粉丝数据
	 */
	public void deleteAllFavoriteToList() {
		db.delete(MY_FAVORITE_TOMY, null, null);
	}

	/**
	 * 获取数据库中的我的粉丝列表
	 * 
	 * @return
	 */
	public ArrayList<User> getAllFavoriteToMyList(int offset) {
		ArrayList<User> list = new ArrayList<User>();
		User mUser = null;
		Cursor c = null;
		try {
			c = db.rawQuery("SELECT * FROM " + MY_FAVORITE_TOMY
					+ " ORDER BY _time desc LIMIT " + (offset + 1)
					* DEFAULT_PAGE_COUNT, null);
			if (c != null && c.getCount() > 0) {
				while (c.moveToNext()) {
					String jid = c.getString(c.getColumnIndex("_jid"));
					String nick = c.getString(c.getColumnIndex("_nick"));
					String sex = c.getString(c.getColumnIndex("_sex"));
					String age = c.getString(c.getColumnIndex("_age"));
					String sig = c.getString(c.getColumnIndex("_sig"));
					String avatar = c.getString(c.getColumnIndex("_avatar"));
					String time = c.getString(c.getColumnIndex("_time"));
					int viplevel = c.getInt(c.getColumnIndex("_viplevel"));
					String halloffame = c.getString(c
							.getColumnIndex("_halloffame"));

					String spellname = c.getString(c
							.getColumnIndex("_namespell"));
					String isfriend = c
							.getString(c.getColumnIndex("_isfriend"));
					String subscription = c.getString(c
							.getColumnIndex("_subscription"));

					int starState = c.getInt(c.getColumnIndex("_starState"));

					mUser = new User();
					mUser.setStarState(starState);
					mUser.setJid(jid);
					mUser.setNick(nick);
					mUser.setSex(sex);
					mUser.setBirthday(age);
					mUser.setSignature(sig);
					mUser.setImageFileId(avatar);
					mUser.setFavorites_time(time);
					mUser.setViplevel(viplevel);
					mUser.setHalloffame(halloffame);
					mUser.setSpellName(spellname);
					mUser.setIsfriend(isfriend);
					mUser.setSubscription(subscription);
					list.add(mUser);
				}
			}
		} catch (Throwable t) {
			ALLog.d(t.toString());
		} finally {
			if (c != null) {
				try {
					c.close();
				} catch (Exception e) {
				}
			}
		}

		ALLog.d("一共有" + list.size() + "粉丝列表");
		return list;
	}

	/**
	 * 搜索数据库中的我的粉丝列表
	 * 
	 * @return
	 */
	public ArrayList<User> searchFavoriteToMyList(String keyword) {
		ArrayList<User> list = new ArrayList<User>();
		User mUser = null;
		Cursor c = null;
		try {
			c = db.rawQuery("SELECT * FROM " + MY_FAVORITE_TOMY
					+ " WHERE _nick like '%" + keyword
					+ "%' ORDER BY _time DESC", null);
			if (c != null && c.getCount() > 0) {
				while (c.moveToNext()) {
					String jid = c.getString(c.getColumnIndex("_jid"));
					String nick = c.getString(c.getColumnIndex("_nick"));
					String sex = c.getString(c.getColumnIndex("_sex"));
					String age = c.getString(c.getColumnIndex("_age"));
					String sig = c.getString(c.getColumnIndex("_sig"));
					String avatar = c.getString(c.getColumnIndex("_avatar"));
					String time = c.getString(c.getColumnIndex("_time"));
					String halloffame = c.getString(c
							.getColumnIndex("_halloffame"));
					int viplevel = c.getInt(c.getColumnIndex("_viplevel"));
					String spellname = c.getString(c
							.getColumnIndex("_namespell"));
					String isfriend = c
							.getString(c.getColumnIndex("_isfriend"));
					String subscription = c.getString(c
							.getColumnIndex("_subscription"));
					int starState = c.getInt(c.getColumnIndex("_starState"));

					mUser = new User();
					mUser.setStarState(starState);
					mUser.setJid(jid);
					mUser.setNick(nick);
					mUser.setSex(sex);
					mUser.setBirthday(age);
					mUser.setSignature(sig);
					mUser.setImageFileId(avatar);
					mUser.setFavorites_time(time);
					mUser.setViplevel(viplevel);
					mUser.setHalloffame(halloffame);
					mUser.setSpellName(spellname);
					mUser.setIsfriend(isfriend);
					mUser.setSubscription(subscription);
					list.add(mUser);
				}
			}
		} catch (Throwable t) {
			ALLog.d(t.toString());
		} finally {
			if (c != null) {
				try {
					c.close();
				} catch (Exception e) {
				}
			}
		}

		ALLog.d("一共有" + list.size() + "粉丝列表");
		return list;
	}

	/**
	 * 获取用户粉丝总数
	 * 
	 * @return count
	 */
	public int getFavotiteToMyCount() {
		int count = 0;
		Cursor c = null;

		String sql = "select count(*) as counts from  " + MY_FAVORITE_TOMY;
		try {
			c = db.rawQuery(sql, null);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (c != null && c.getCount() > 0) {

			while (c.moveToNext()) {
				count = c.getInt(c.getColumnIndex("counts"));
			}
		}

		if (c != null) {
			c.close();
		}

		ALLog.d("该用户粉丝的总数 count:" + count);
		return count;
	}

	public int getViewUserInfoCountByJid(String jid) {

		String[] args = new String[] { jid };
		Cursor c = null;
		int count = 0;
		try {
			c = db.rawQuery("SELECT * FROM " + MY_SUBSCRIBE_TIPS
					+ " WHERE _jid=?", args);
			if (c != null && c.getCount() > 0) {
				if (c.moveToNext()) {
					count = c.getInt(c.getColumnIndex("_viewcount"));
				}
			}
		} catch (Throwable t) {
			ALLog.d(t.toString());
		} finally {
			if (c != null) {
				try {
					c.close();
				} catch (Exception e) {
				}
			}
		}
		return count;
	}

	public void insertViewuserInfoCountByjid(String jid, int count) {
		ContentValues values = new ContentValues();
		values.put("_viewcount", count);
		values.put("_jid", jid);

		if (db.insert(MY_SUBSCRIBE_TIPS, "", values) == -1) {
			ALLog.d("插入訂閱提示 失败");
			return;
		}
		ALLog.d("插入訂閱提示 成功");
	}

	public void setViewUserInfoCountByJid(String jid, int count) {

		String[] arg = { jid };
		ContentValues values = new ContentValues();
		values.put("_viewcount", count);
		if (db.update(MY_SUBSCRIBE_TIPS, values, "_jid=?", arg) == -1) {
			ALLog.d("更新訂閱提示 失败");
		}
		ALLog.d("更新訂閱提示成功 " + count);
	}

	public int getNewViewUserJidSum() {

		int count = 0;
		Cursor c = null;
		try {
			c = db.rawQuery("SELECT * FROM " + USER_INFO_GUIDER_TABLE, null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			count = c.getCount();
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d("getNewViewUserJidSum 中一共有" + count + " 个jid!");

		return count;

	}

	public int getNewViewUserInfoCountByJid(String jid) {

		String[] args = new String[] { jid };
		Cursor c = null;
		int count = 0;
		try {
			c = db.rawQuery("SELECT * FROM " + USER_INFO_GUIDER_TABLE
					+ " WHERE _jid=?", args);
			if (c != null && c.getCount() > 0) {
				if (c.moveToNext()) {
					count = c.getInt(c.getColumnIndex("_viewcount"));
				}
			}
		} catch (Throwable t) {
			ALLog.d(t.toString());
		} finally {
			if (c != null) {
				try {
					c.close();
				} catch (Exception e) {
				}
			}
		}
		return count;
	}

	public void insertNewViewuserInfoCountByjid(String jid, int count) {
		ContentValues values = new ContentValues();
		values.put("_viewcount", count);
		values.put("_jid", jid);

		if (db.insert(USER_INFO_GUIDER_TABLE, "", values) == -1) {
			ALLog.d("插入訂閱提示 失败");
			return;
		}
		ALLog.d("插入訂閱提示 成功");
	}

	public void setNewViewUserInfoCountByJid(String jid, int count) {

		String[] arg = { jid };
		ContentValues values = new ContentValues();
		values.put("_viewcount", count);
		if (db.update(USER_INFO_GUIDER_TABLE, values, "_jid=?", arg) == -1) {
			ALLog.d("更新訂閱提示 失败");
		}
		ALLog.d("更新訂閱提示成功 " + count);
	}

	public boolean isFirstUse() {

		Cursor c = null;
		int count = 0;
		try {
			c = db.rawQuery("SELECT * FROM " + USE_STATE_TABLE, null);
			if (c != null && c.getCount() > 0) {
				if (c.moveToNext()) {
					count = c.getInt(c.getColumnIndex("_firstuse"));
				}
			}
		} catch (Throwable t) {
			ALLog.d(t.toString());
		} finally {
			if (c != null) {
				try {
					c.close();
				} catch (Exception e) {
				}
			}
		}

		if (count == 0)
			return false;
		return true;
	}

	public boolean isFirstViewMaster() {

		Cursor c = null;
		int count = 0;
		try {
			c = db.rawQuery("SELECT * FROM " + USE_STATE_TABLE, null);
			if (c != null && c.getCount() > 0) {
				if (c.moveToNext()) {
					count = c.getInt(c.getColumnIndex("_firstviewmaster"));
				}
			}
		} catch (Throwable t) {
			ALLog.d(t.toString());
		} finally {
			if (c != null) {
				try {
					c.close();
				} catch (Exception e) {
				}
			}
		}

		if (count == 0)
			return false;
		return true;

	}

	public void updateFirstUseState() {
		ContentValues values = new ContentValues();
		values.put("_firstuse", 1);
		// USER_INFO_GUIDER_TABLE, values, "_jid=?", arg
		if (db.update(USE_STATE_TABLE, values, null, null) == -1) {
			return;
		}
	}

	public void updateFirstViewMasterState() {

		ContentValues values = new ContentValues();
		values.put("_firstviewmaster", 1);

		if (db.update(USE_STATE_TABLE, values, null, null) == -1) {
			return;
		}
	}

	private ArrayList<String> getColumns(SQLiteDatabase db, String tabname) {
		ALLog.d("searching " + tabname);
		ArrayList<String> cols = new ArrayList<String>();

		Cursor ti = db.rawQuery("PRAGMA table_info(" + tabname + ")", null);

		if (ti.moveToFirst()) {
			do {
				// System.out.println("col: " + ti.getString(1));
				cols.add(ti.getString(1));
			} while (ti.moveToNext());
		}
		// for (String s : cols) {
		// ALLog.d( "column: " + s);
		// }

		if (ti != null) {
			try {
				ti.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return cols;
	}

	public boolean isDataBaseUpdate() {
		return isUpdate;
	}

	// ///////////////////////////// 黑名单 /////////////////////////////////
	/**
	 * 将用户插入黑名单列表
	 * 
	 * @param u
	 */
	public void insertUserToBlackList(User u) {

		ContentValues values = new ContentValues();
		values.put("_imagefileid", u.getImageFileId());
		values.put("_nick", u.getNick());
		values.put("_jid", u.getJid());
		values.put("_time", System.currentTimeMillis() / 1000);

		if (db.insert(USER_BLACK_LIST_TABLE, "", values) == -1) {
			ALLog.d("插入黑名单 失败");
			return;
		}
		ALLog.d("插入黑名单成功");
	}

	/**
	 * 获取黑名单用户
	 * 
	 * @return
	 */
	public ArrayList<User> getBlackListUsers() {
		ArrayList<User> users = new ArrayList<User>();

		Cursor c = null;

		try {
			c = db.rawQuery("SELECT * FROM " + USER_BLACK_LIST_TABLE
					+ " ORDER BY _time DESC", null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			User d = null;
			while (c.moveToNext()) {
				d = new User();

				d.setJid(c.getString(c.getColumnIndex("_jid")));
				d.setImageFileId(c.getString(c.getColumnIndex("_imageFileid")));
				d.setNick(c.getString(c.getColumnIndex("_nick")));

				if (!users.contains(d)) {
					users.add(d);
				}
			}
			d = null;
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}
		ALLog.d("黑名单列表中一共有  " + users.size());
		return users;
	}

	/**
	 * 获取黑名单长度
	 * 
	 * @return
	 */
	public int getBlackListSize() {
		Cursor c = null;
		int count = 0;
		try {
			c = db.rawQuery("SELECT * FROM " + USER_BLACK_LIST_TABLE
					+ " ORDER BY _time DESC", null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			count = c.getCount();
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}
		ALLog.d("黑名单列表中一共有  " + count);
		return count;
	}

	/**
	 * 更新黑名单中的用户昵称和头像
	 * 
	 * @param u
	 */
	public void updateBlackUserInfo(User u) {
		if (u == null)
			return;
		String[] args = { u.getJid() };
		ContentValues values = new ContentValues();
		values.put("_nick", u.getNick());
		values.put("_imageFileid", u.getImageFileId());
		if (db.update(USER_BLACK_LIST_TABLE, values, "_jid=?", args) != -1) {
			ALLog.d("更新黑名单用户成功");
		}
	}

	/**
	 * 将指定用户从黑名单中删除
	 * 
	 * @param jid
	 */
	public void deleteUserFromBlackList(String jid) {
		String[] arg = { jid };
		if (db.delete(USER_BLACK_LIST_TABLE, "(_jid=?)", arg) != -1) {
			ALLog.d("删除jid为" + jid + "的黑名单记录成功");
			return;
		}
		ALLog.d("删除jid为" + jid + "的黑名单记录失败");

	}

	/**
	 * 清空黑名单
	 */
	public void deletBlackList() {
		db.delete(USER_BLACK_LIST_TABLE, null, null);
	}

	/************************************* 通话记录 ******************************************/

	/**
	 * 根据通话id读取通话记录信息
	 * 
	 * @param callId
	 * @return
	 */
	public ALMessage getCallHistoryByCallId(String callId) {
		ALMessage msg = null;

		Cursor c = null;

		try {
			c = db.rawQuery("SELECT * FROM " + VOIP_CALL_HISTORY_TABLE
					+ " where _callid=" + callId, null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			User d = null;
			while (c.moveToNext()) {
				msg = new ALMessage();
				d = new User();
				d.setJid(c.getString(c.getColumnIndex("_jid")));
				d.setImageFileId(c.getString(c.getColumnIndex("_imageFileid")));
				d.setNick(c.getString(c.getColumnIndex("_nick")));
				d.setIsCaller(c.getInt(c.getColumnIndex("_iscaller")) == 1 ? true
						: false);

				d.setCallRecordType(c.getInt(c.getColumnIndex("_callstate")));
				d.setVauthed(c.getInt(c.getColumnIndex("_isVauth")));
				d.setSex(c.getString(c.getColumnIndex("_sex")));
				d.setIsfriend(c.getInt(c.getColumnIndex("_isfriend")) == 1 ? "1"
						: "0");

				msg.setDate(new Date(c.getLong(c.getColumnIndex("_time"))));
				msg.setMsgId(c.getString(c.getColumnIndex("_callid")));
				msg.setDisplayed(c.getInt(c.getColumnIndex("_state")) == 1 ? true
						: false);
				msg.setCallTime(c.getInt(c.getColumnIndex("_calltime")));
				msg.setData(d);
			}
			d = null;
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		return msg;
	}

	/**
	 * 獲取所有通話記錄列表
	 * 
	 * @return
	 */
	public ArrayList<ALMessage> getCallHistory() {
		ArrayList<ALMessage> callHistory = new ArrayList<ALMessage>();
		ALMessage msg;
		Cursor c = null;

		try {
			c = db.rawQuery("SELECT * FROM " + VOIP_CALL_HISTORY_TABLE
					+ " ORDER BY _time DESC", null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			User d = null;
			while (c.moveToNext()) {
				msg = new ALMessage();
				d = new User();
				d.setJid(c.getString(c.getColumnIndex("_jid")));
				d.setImageFileId(c.getString(c.getColumnIndex("_imageFileid")));
				d.setNick(c.getString(c.getColumnIndex("_nick")));
				d.setIsCaller(c.getInt(c.getColumnIndex("_iscaller")) == 1 ? true
						: false);

				d.setCallRecordType(c.getInt(c.getColumnIndex("_callstate")));
				d.setVauthed(c.getInt(c.getColumnIndex("_isVauth")));
				d.setSex(c.getString(c.getColumnIndex("_sex")));
				d.setIsfriend(c.getInt(c.getColumnIndex("_isfriend")) == 1 ? "1"
						: "0");

				msg.setDate(new Date(c.getLong(c.getColumnIndex("_time"))));
				msg.setMsgId(c.getString(c.getColumnIndex("_callid")));
				msg.setDisplayed(c.getInt(c.getColumnIndex("_state")) == 1 ? true
						: false);
				msg.setCallTime(c.getInt(c.getColumnIndex("_calltime")));
				msg.setData(d);

				if (!callHistory.contains(msg)) {
					callHistory.add(msg);
				}
			}
			d = null;
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		return callHistory;
	}

	/**
	 * 獲取通話記錄列表
	 * 
	 * @return
	 */
	public ArrayList<ALMessage> getCallHistoryByFriendship(boolean isFriend) {
		ArrayList<ALMessage> callHistory = new ArrayList<ALMessage>();
		ALMessage msg;
		Cursor c = null;

		String[] arg = { isFriend ? "1" : "0" };

		String sql = "SELECT * FROM " + VOIP_CALL_HISTORY_TABLE
				+ " where _isfriend=?" + " ORDER BY _time DESC";

		try {
			// c = db.rawQuery("SELECT * FROM " + VOIP_CALL_HISTORY_TABLE
			// + " ORDER BY _time DESC", null);
			c = db.rawQuery(sql, arg);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			User d = null;
			while (c.moveToNext()) {
				msg = new ALMessage();
				d = new User();
				d.setJid(c.getString(c.getColumnIndex("_jid")));
				d.setImageFileId(c.getString(c.getColumnIndex("_imageFileid")));
				d.setNick(c.getString(c.getColumnIndex("_nick")));
				d.setIsCaller(c.getInt(c.getColumnIndex("_iscaller")) == 1 ? true
						: false);

				d.setCallRecordType(c.getInt(c.getColumnIndex("_callstate")));
				d.setVauthed(c.getInt(c.getColumnIndex("_isVauth")));
				d.setSex(c.getString(c.getColumnIndex("_sex")));
				d.setIsfriend(c.getInt(c.getColumnIndex("_isfriend")) == 1 ? "1"
						: "0");

				msg.setDate(new Date(c.getLong(c.getColumnIndex("_time"))));
				msg.setMsgId(c.getString(c.getColumnIndex("_callid")));
				msg.setDisplayed(c.getInt(c.getColumnIndex("_state")) == 1 ? true
						: false);
				msg.setCallTime(c.getInt(c.getColumnIndex("_calltime")));
				msg.setData(d);

				if (!callHistory.contains(msg)) {
					callHistory.add(msg);
				}
			}
			d = null;
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		return callHistory;
	}

	/**
	 * 獲取通話記錄長度
	 * 
	 * @return
	 */
	public int getCallHistorySize() {
		Cursor c = null;
		int count = 0;
		try {
			c = db.rawQuery("SELECT * FROM " + VOIP_CALL_HISTORY_TABLE
					+ " ORDER BY _time DESC", null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {
			count = c.getCount();
		}
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}
		ALLog.d("通話記錄列表中一共有  " + count);
		return count;
	}

	/**
	 * 保存新的通话记录
	 * 
	 * @param call
	 */
	public void insertCallHistory(ALMessage call) {

		User user = (User) call.getData();

		ContentValues values = new ContentValues();
		values.put("_iscaller", user.isCaller() ? 1 : 0);
		values.put("_calltime", call.getCallTime());
		values.put("_time", call.getDate().getTime());
		values.put("_callstate", user.getCallRecordType());
		values.put("_callid", call.getMsgId());
		values.put("_isfriend", user.getIsfriend() ? 1 : 0);

		values.put("_imageFileid", user.getImageFileId());
		values.put("_nick", user.getNick());
		values.put("_jid", user.getJid());
		values.put("_isVauth", user.getVauthed());
		values.put("_sex", user.getSex());

		// 根据已读状态，写入数据库
		if (call.getDisplayed()) {
			values.put("_state", 1);
		} else {
			values.put("_state", 0);
		}

		if (!isCallHistoryExist(user.getJid())) {
			try {
				if (db.insert(VOIP_CALL_HISTORY_TABLE, "", values) == -1) {
					ALLog.d("保存通话记录失败 ");
					return;
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			ALLog.d("保存通话记录成功 ");
		} else {
			// 更新通话记录
			try {
				String[] arg = { user.getJid() };
				if (db.update(VOIP_CALL_HISTORY_TABLE, values, "_jid=?", arg) == -1) {
					ALLog.d("更新通话记录失败 ");
					return;
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			ALLog.d("更新通话记录成功 ");
		}

	}

	/**
	 * 是否有正在约会的记录
	 * 
	 * @return true 有; false 没有
	 */
	public boolean isCallHistoryExist(String jid) {
		boolean isExist = false;
		String[] arg = { jid };

		Cursor c = null;

		try {
			c = db.rawQuery("select * from " + VOIP_CALL_HISTORY_TABLE
					+ " where _jid=?", arg);
		} catch (Throwable t) {
			t.printStackTrace();
		}

		if ((c != null) && (c.getCount() > 0)) {
			isExist = true;
		}

		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
			}
		}

		ALLog.d((isExist ? "有" : "没有") + "与" + jid + "的通话记录");
		return isExist;
	}

	/**
	 * 删除指定的通话记录
	 * 
	 * @param callId
	 */
	public void deleteCallHistory(String callId) {
		String[] arg = { callId };
		if (db.delete(VOIP_CALL_HISTORY_TABLE, "(_callid=?)", arg) != -1) {
			ALLog.d("刪除通話記錄失敗 " + callId);
			return;
		}
		ALLog.d("刪除通話記錄成功 " + callId);
	}

	/**
	 * 清除所有通話記錄
	 */
	public void deleteAllCallHitory() {
		db.delete(VOIP_CALL_HISTORY_TABLE, null, null);
	}

	/**
	 * 获取未读来电提醒未接来电数目
	 * 
	 * @param isCallNotice
	 * @return
	 */
	public int getUnReadCallHistoryByMissStype(boolean isCallNotice) {

		String[] arg = { isCallNotice ? "" + User.CALL_STATE_CALL_NOTIFY : ""
				+ User.CALL_STATE_MISS };
		int i = 0;
		Cursor c = null;
		try {
			c = db.rawQuery("SELECT count(*) as counts FROM "
					+ VOIP_CALL_HISTORY_TABLE
					+ " where _state=0 and _callstate=?", arg);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {

			if (c.moveToNext()) {
				i = c.getInt(c.getColumnIndex("counts"));
			}
		}

		if (c != null) {
			c.close();
		}
		return i;

	}

	/**
	 * 获取未读通话记录条目数
	 * 
	 * @return
	 */
	public int getUnReadCallHistory() {

		int i = 0;
		Cursor c = null;
		try {
			c = db.rawQuery("SELECT count(*) as counts FROM "
					+ VOIP_CALL_HISTORY_TABLE + " where _state=0", null);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {

			if (c.moveToNext()) {
				i = c.getInt(c.getColumnIndex("counts"));
			}
		}

		if (c != null) {
			c.close();
		}
		return i;
	}

	/**
	 * 根據好友與否條件,获取未读通话记录条目数
	 * 
	 * @return
	 */
	public int getUnReadCallHistoryByFriendShip(boolean isFriend) {

		int i = 0;

		String[] arg = { isFriend ? "1" : "0" };

		Cursor c = null;
		try {
			c = db.rawQuery("SELECT count(*) as counts FROM "
					+ VOIP_CALL_HISTORY_TABLE
					+ " where _state=0 and _isfriend=?", arg);
		} catch (Throwable t) {
			ALLog.d(t.toString());
		}

		if (c != null && c.getCount() > 0) {

			if (c.moveToNext()) {
				i = c.getInt(c.getColumnIndex("counts"));
			}
		}

		if (c != null) {
			c.close();
		}
		return i;
	}

	/**
	 * 将通话记录设为已读
	 * 
	 * @param callId
	 */
	public void setCallHistoryReaded(String callId) {

		String[] arg = { callId };
		ContentValues values = new ContentValues();
		values.put("_state", 1);
		db.update(VOIP_CALL_HISTORY_TABLE, values, "_callid=?", arg);
	}

	/**
	 * 设置所有临时通话为已读
	 */
	public void setAllTempCallHistoryReaded() {
		ContentValues values = new ContentValues();
		values.put("_state", 1);
		db.update(VOIP_CALL_HISTORY_TABLE, values, "_isfriend=0", null);
	}

	/**
	 * 设置所有好友通话为已读
	 */
	public void setAllFriendsCallHistoryReaded() {
		ContentValues values = new ContentValues();
		values.put("_state", 1);
		db.update(VOIP_CALL_HISTORY_TABLE, values, "_isfriend=1", null);
	}

	/**
	 * 更新通話狀態
	 * 
	 * @param callId
	 * @param state
	 */
	public void updateCallHitstroyState(String callId, int state) {
		String[] arg = { callId };
		ContentValues values = new ContentValues();
		values.put("_callstate", state);
		db.update(VOIP_CALL_HISTORY_TABLE, values, "_callid=?", arg);
	}

	/**
	 * 更新通话记录用户资料
	 * 
	 * @param user
	 */
	public void updateCallHitoryUserProfile(User u) {
		if (u == null)
			return;
		String[] args = { u.getJid() };
		ContentValues values = new ContentValues();
		values.put("_nick", u.getNick());
		values.put("_imageFileid", u.getImageFileId());
		values.put("_isVauth", u.getVauthed());
		if (db.update(VOIP_CALL_HISTORY_TABLE, values, "_jid=?", args) != -1) {
		}
	}

	/**
	 * 更新通话时间
	 * 
	 * @param callId
	 * @param time
	 */
	public void updateCallingTime(String callId, int time) {
		String[] args = { callId };
		ContentValues values = new ContentValues();
		values.put("_calltime", time);
		if (db.update(VOIP_CALL_HISTORY_TABLE, values, "_callid=?", args) != -1) {
		}
	}

	/**
	 * 更新通话记录中的好友状态
	 * 
	 * @param jid
	 * @param isFriend
	 */
	public boolean updateCallUserFriendShip(String jid, boolean isFriend) {
		String[] args = { jid };
		ContentValues values = new ContentValues();
		values.put("_isfriend", isFriend ? 1 : 0);
		return db.update(VOIP_CALL_HISTORY_TABLE, values, "_jid=?", args) != -1 ? true
				: false;

	}

	private class AccountDBHelper extends SQLiteOpenHelper {

		public AccountDBHelper(Context context, String name, int version) {
			super(context, name, null, version);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {

			ALLog.d("创建AccountDBHelper数据库");
			try {

				// 创建我的约会详细记录
				db.execSQL("CREATE TABLE IF NOT EXISTS " + MY_PRIVATE_ACCOUNT
						+ " (_jid TEXT)");

			} catch (Throwable t) {
				t.printStackTrace();
			}

		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

		}

	}

	private class MyOpenHelper extends SQLiteOpenHelper {

		private String db_name;

		private String[] tables;

		public MyOpenHelper(Context context, String name, int version) {
			super(context, name, null, version);
			ALLog.d("打开数据库" + name);
			this.db_name = name;
		}

		/**
		 * 测试tableName在数据库中是否存在
		 * 
		 * @param db
		 *            数据库实例
		 * @param tableName
		 *            表名
		 * @return true表存在。false不存在
		 */
		private boolean isTableExist(SQLiteDatabase db, String tableName) {
			boolean result = false;

			if (tableName == null) {
				return false;
			}
			Cursor cursor = null;
			try {
				String sql = "select count(*) from Sqlite_master  where type ='table' and name ='"
						+ tableName.trim() + "' ";
				cursor = db.rawQuery(sql, null);
				if (cursor.moveToNext()) {
					int count = cursor.getInt(0);
					if (count > 0) {
						cursor.close();
						result = true;
					}
				}

			} catch (Exception e) {
				ALLog.d("check table exits failed: " + e.toString());
			}
			cursor.close();
			return result;
		}

		private String[] getAllTables(SQLiteDatabase db) {
			String[] result = null;
			try {
				StringBuilder sb = new StringBuilder();
				sb.append("SELECT name FROM sqlite_master ");
				sb.append("WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' ");
				sb.append("UNION ALL ");
				sb.append("SELECT name FROM sqlite_temp_master ");
				sb.append("WHERE type IN ('table','view') ");
				sb.append("ORDER BY 1");
				String tableName = null;
				Cursor c = db.rawQuery(sb.toString(), null);
				if (c != null) {
					c.moveToFirst();

					result = new String[c.getCount()];
					int i = 0;
					while (c.moveToNext()) {
						tableName = c.getString(c.getColumnIndex("name"));
						if (!TextUtils.isEmpty(tableName)) {
							result[i] = tableName;
							i++;
						}
					}
					c.close();
				}
			} catch (SQLiteException e) {
				ALLog.d(e.toString());
			}
			for (String s : result) {
				ALLog.d("表名 " + s);
			}

			return result;
		}

		// 更新数据库的表
		@Override
		public void onUpgrade(SQLiteDatabase arg0, int oldVersion,
				int newVersion) {
			ALLog.d("version is " + oldVersion + "," + newVersion);
			try {
				isUpdate = true;
				this.oldVersion = oldVersion;
				// 将原有的表重命名
				renameOldTable(arg0);
				onCreate(arg0);

				// 恢复备份数据
				insertBak(arg0);
			} catch (Exception e) {
				e.printStackTrace();
				ALLog.d("迁移数据库出错: " + e.toString());
			}

		}

		/**
		 * 将原有的表重命名
		 * 
		 * @param db
		 *            SQLiteDatabase实例
		 */
		private void renameOldTable(SQLiteDatabase db) {

			// 得到当前表名
			tables = getAllTables(db);

			for (String s : tables) {
				if (isTableExist(db, s)) {
					// 把老表重命名
					db.execSQL("alter table " + s + " rename to " + s
							+ DATABASE_TMP_SUFIX);
					ALLog.d("重命名表 " + s + " 为 " + s + DATABASE_TMP_SUFIX);
				}
			}
		}

		private void recoverForSpecTable(SQLiteDatabase db, String oldTable,
				String newTable) {
			ArrayList<String> oldCols = getColumns(db, oldTable);
			ArrayList<String> newCols = getColumns(db, newTable);
			String sql = "";
			for (String s : newCols) {
				if (oldCols.contains(s)) {
					sql += s + ",";
				}
			}

			if (isTableExist(db, oldTable)) {
				if (!sql.equals("")) {
					String s = sql.substring(0, sql.length() - 1);
					sql = "insert into " + newTable + " (" + s + ") "
							+ "  select  " + s + "  from  " + oldTable;
					db.execSQL(sql);
					ALLog.d("正在执行迁移语句: " + sql);
				}
				// 删除老表
				db.execSQL("DROP TABLE IF EXISTS " + oldTable);
				ALLog.d("删除老表: " + oldTable);
			}
		}

		/**
		 * 将老版本表的数据导入到新表中
		 * 
		 * @param db
		 */
		private void insertBak(SQLiteDatabase db) {

			for (String s : tables) {
				ALLog.d("重新插表 " + s);
				recoverForSpecTable(db, s + DATABASE_TMP_SUFIX, s);
			}

			renameDataBase(db);
			ALLog.d("Recover Success");
		}

		private void renameDataBase(SQLiteDatabase database) {
			getDefaultDataUsername(database);

			if (db_name.equals(DB_NAME)) {
				ALAccount account = getDefaultDataUsername(database);
				if (!TextUtils.isEmpty(account.getUserName())) {
					String parent = ALLocalEnv.getLocalEnv()
							.getDatabasePath(DB_NAME).getParent();
					ALLocalEnv
							.getLocalEnv()
							.getDatabasePath(DB_NAME)
							.renameTo(
									new File(parent + "/"
											+ account.getUserName() + ".db"));
					ALLog.d("将原有数据库更名" + account.getUserName() + ".db");
					curUsername = account.getUserName();
				}
			}
		}

		private ALAccount getDefaultDataUsername(SQLiteDatabase db) {
			ALAccount account = new ALAccount();

			Cursor c = null;

			try {
				c = db.rawQuery("SELECT * FROM " + MY_ACCOUNT, null);
			} catch (Throwable t) {
				ALLog.d("loadMyAccount" + t.toString());
			}

			if (c != null && c.getCount() > 0) {
				while (c.moveToNext()) {
					account.setUserName(c.getString(c
							.getColumnIndex("_username")));
					account.setPassWord(c.getString(c
							.getColumnIndex("_password")));
					account.setCustomName(c.getString(c
							.getColumnIndex("_customName")));
					account.setLoginType(c.getInt(c
							.getColumnIndex("_loginType")));
				}
			}
			if (c != null) {
				try {
					c.close();
				} catch (Exception e) {
				}
			}

			if (account.getUserName() != null) {
				if (account.getUserName().equals("")) {
					account.setUserName(null);
				}
			}

			ALLog.d("用户名:" + account.getUserName() + "\n密码:"
					+ account.getPassWord() + "\n登录类型" + account.getLoginType());

			return account;
		}

		private int oldVersion = -1;

		// 创建数据库表
		@Override
		public void onCreate(SQLiteDatabase db) {

			ALLog.d("创建数据库");
			try {

				// 创建我的约会详细记录
				db.execSQL("CREATE TABLE IF NOT EXISTS "
						+ MY_DATE_RECORDS
						+ " (_jid TEXT ,_nick TEXT,_imageFileid TEXT,_place TEXT,_duration TEXT, _time INTEGER, _vip INTEGER, UNIQUE(_time))");

				// 创建我的约会列表
				db.execSQL("CREATE TABLE IF NOT EXISTS "
						+ MY_DATE_HISTORY
						+ " (_jid TEXT ,_nick TEXT,_imageFileid TEXT,_place TEXT,_duration TEXT, _time INTEGER, _vip INTEGER, UNIQUE(_time))");

				// 创建我的约会聊天记录表
				db.execSQL("CREATE TABLE IF NOT EXISTS "
						+ MY_DATE_RECORDS_MESSAGE
						+ "(_deliverStste INTEGER,_jid TEXT , _msgId TEXT,_time TIMESTAMP,_type INTEGER, _from TEXT,_to TEXT,_body TEXT,_fromNick TEXT,_toNick TEXT,_subject TEXT,_reclen TEXT,_path TEXT, _state INTEGER, _fileId TEXT,_faceId TEXT ,_faceName TEXT,_isFromWaiter INTEGER, UNIQUE(_msgId))");

				// 创建系统消息
				db.execSQL("CREATE TABLE IF NOT EXISTS "
						+ SYSTEM_MESSAGE
						+ " (_org_logo TEXT,_button_url1 TEXT,_button_url2 TEXT,_button_name1 TEXT,_button_name2 TEXT,_time INTEGER,_from TEXT,_body TEXT,_fromNick TEXT,_subject TEXT,_msgId TEXT,_state INTEGER,_type TEXT,_fromAvatar TEXT,_linkBody TEXT,UNIQUE(_msgId))");

				// 创建我的礼物列表
				db.execSQL("CREATE TABLE IF NOT EXISTS "
						+ MY_GIFTS_LIST
						+ " (_giftid TEXT,_fileid TEXT,_giftname TEXT,_fromNick TEXT,_count TEXT,_type TEXT)");

				// 创建当前系统礼物列表
				db.execSQL("CREATE TABLE IF NOT EXISTS "
						+ CUR_GIFT_LIST
						+ " (_value LONG,_hot LONG,_sell LONG,_moneyType TEXT,_desc TEXT,_desc2 TEXT,_giftid TEXT,_fileid TEXT,_giftname TEXT,_price TEXT,_viprice TEXT,_pricevip2 TEXT,_pricevip3 TEXT,_imagePath TEXT,_type TEXT,_exchangecount TEXT,_points TEXT,_precious TEXT, _categoryId TEXT default '', _isTimerGift INTEGER, _isLimitGift INTEGER,_isHotGift INTEGER,_isMingrenGift INTEGER,_isCustom INTEGER)");

				// 账号密码
				db.execSQL("CREATE TABLE IF NOT EXISTS "
						+ MY_ACCOUNT
						+ " (_username TEXT,_password TEXT,_customName TEXT,_loginType INTEGER)");

				// 我的充值记录
				db.execSQL("CREATE TABLE IF NOT EXISTS " + MY_RECHARGE_RECORD
						+ " (_type INTEGER, _orderid TEXT,_productid TEXT)");

				// 系统设置
				db.execSQL("CREATE TABLE IF NOT EXISTS " + SYSTEM_SETTING
						+ " (_state INTEGER)");

				db.execSQL("CREATE TABLE IF NOT EXISTS "
						+ MY_MESSAGE_RECORD
						+ " (_answer TEXT, _intimateid TEXT, _button_url1 TEXT,_button_url2 TEXT,_button_name1 TEXT,_button_name2 TEXT,_jid TEXT,_time TIMESTAMP,_from TEXT,_to TEXT,_body TEXT,_body2 TEXT,_body3 TEXT,_fromNick TEXT,_toNick TEXT,_subject TEXT,_msgId TEXT, _state INTEGER,_fileId TEXT,_type TEXT, _plaza INTEGER,_audiofileid TEXT,_sex TEXT,_vauth TEXT, UNIQUE(_msgId))");

				// 登录统计
				db.execSQL("CREATE TABLE IF NOT EXISTS "
						+ USER_LOGIN_HISTORY
						+ "( _jid TEXT , _to_jid TEXT, _time INTEGER, _scene TEXT)");

				// 拒绝约会邀请统计
				db.execSQL("CREATE TABLE IF NOT EXISTS " + USER_REFUSE_HISTORY
						+ "(_jid TEXT, _refuse TEXT)");

				// 系统配置选项
				db.execSQL("CREATE TABLE IF NOT EXISTS "
						+ LOCAL_CONFIGURE
						+ "(_lat TEXT, _lng TEXT, _imip TEXT, _import TEXT,_imhttpport TEXT, _domain TEXT, _mediaip TEXT, _mediaport TEXT, _newsurl TEXT)");

				// 被收藏记录
				db.execSQL("CREATE TABLE IF NOT EXISTS " + FAVOTITE_HISTORY
						+ "(_from TEXT, _body TEXT, UNIQUE(_from))");

				// 约会记录
				db.execSQL("CREATE TABLE IF NOT EXISTS "
						+ DATING_RECORD
						+ "(_responsed INTEGER,_createType INTEGER,_ballid TEXT , _jid TEXT , _nick TEXT, _isVip INTEGER, _imageFileid TEXT, "
						+ "_place TEXT, _time LONG, _duration TEXT, _scene TEXT, _sceneName TEXT, _sex TEXT, _distance TEXT, "
						+ "_userPopularity TEXT, _status INTEGER, _birthday TEXT, _isAppointting INTEGER, _lastMsgTime TIMESTAMP, "
						+ "_isExistMsg INTEGER, _isExistUnreadMsg INTEGER,_viplevel TEXT,_lastRecord TEXT,_lastMsg TEXT,_customScene TEXT,"
						+ "_star INTEGER)");

				// 创建礼物分类列表
				db.execSQL("CREATE TABLE IF NOT EXISTS  " + GIFT_CATEGORY_LIST
						+ "(_id TEXT, _name TEXT, _fileid TEXT, _fileid2 TEXT)");

				// 创建道具信息表
				db.execSQL("CREATE TABLE IF NOT EXISTS "
						+ MY_PROPS_MAILL_LIST
						+ " (_props TEXT, _propsname TEXT,_propstype TEXT,_propstypename TEXT, _fileid TEXT, _propslevel TEXT, _propindex TEXT, _propsindex TEXT, _desc TEXT,UNIQUE(_props))");

				// 创建最近@的人
				db.execSQL("CREATE TABLE IF NOT EXISTS  "
						+ MY_PLAZA_LASTED_ADD_USER
						+ "(_jid TEXT,_nick TEXT,_imagefileid TEXT,_addtime TEXT) ");

				// new数量表
				db.execSQL("CREATE TABLE IF NOT EXISTS " + NEW_COUNT_TABLE
						+ " (_key TEXT, _count int)");

				db.execSQL("CREATE TABLE IF NOT EXISTS "
						+ MY_FAVORITE_FORMY
						+ " (_starState INTEGER,_halloffame TEXT ,_isspecial Text,_namespell TEXT,_isfriend TEXT,_subscription TEXT,_subendtime TEXT,_jid TEXT ,_nick TEXT,_sex TEXT,_age TEXT,_sig TEXT,_avatar TEXT,_viplevel INTEGER)");
				db.execSQL("CREATE TABLE IF NOT EXISTS "
						+ MY_FAVORITE_TOMY
						+ " (_starState INTEGER,_halloffame TEXT,_namespell TEXT,_isfriend TEXT,_subscription TEXT,_jid TEXT ,_nick TEXT,_sex TEXT,_age TEXT,_sig TEXT,_avatar TEXT,_time TEXT,_viplevel INTEGER)");

				// 订阅TIPS
				db.execSQL("CREATE TABLE IF NOT EXISTS " + MY_SUBSCRIBE_TIPS
						+ " ( _jid TEXT ,_viewcount INTEGER)");

				// 订阅TIPS
				db.execSQL("CREATE TABLE IF NOT EXISTS "
						+ USER_INFO_GUIDER_TABLE
						+ " ( _jid TEXT ,_viewcount INTEGER)");

				// 记录粉丝和好友个数
				db.execSQL("CREATE TABLE IF NOT EXISTS  "
						+ FANS_AND_FRIENDS_COUNT
						+ "(_fans_count TEXT,_friends_count TEXT)");

				// 记录区域
				db.execSQL("CREATE TABLE IF NOT EXISTS  " + SELECT_REGION
						+ "(_region TEXT)");

				// 黑名单
				db.execSQL("CREATE TABLE IF NOT EXISTS  "
						+ USER_BLACK_LIST_TABLE
						+ "(_jid TEXT,_nick TEXT,_imageFileid TEXT, _time INTEGER,UNIQUE(_jid)) ");

				// 通话记录VOIP_CALL_HISTORY_TABLE
				db.execSQL("CREATE TABLE IF NOT EXISTS  "
						+ VOIP_CALL_HISTORY_TABLE
						+ "(_isfriend INTEGER,_iscaller INTEGER,_state INTEGER, _callstate INTEGER,_calltime INTEGER,_isMissed INTEGER,_jid TEXT,_sex TEXT,_nick TEXT,_imageFileid TEXT,_isVauth INTEGER, _time INTEGER, _callid TEXT,UNIQUE(_jid)) ");

				if (oldVersion != -1) {// 表示覆盖安装
					switch (oldVersion) {
					case 0:
					case 1:
					case 2:
					case 3:
					case 4:
					case 5:
					case 6:
					case 7:
					case 8:
					case 9:
					case 10:
						createIndex();
					}
				} else {// 表示重新安装
					createIndex();
				}

			} catch (Throwable t) {
				t.printStackTrace();
			}
		}
	}

	/**
	 * 新建索引
	 */
	private void createIndex() {
		ALLog.d("新建相关索引");
		// 新建部分表索引
		db.execSQL("CREATE INDEX MY_DATE_RECORDS_Index ON MY_DATE_RECORDS (_jid)");
		db.execSQL("CREATE INDEX MY_DATE_HISTORY_Index ON MY_DATE_RECORDS (_jid)");
		db.execSQL("CREATE INDEX MY_DATE_RECORDS_MESSAGE_Index ON MY_DATE_RECORDS (_jid)");
		db.execSQL("CREATE DATING_RECORD_Index ON MY_DATE_RECORDS (_jid)");
	}

	/**
	 * @Title: checkCollectionListNullColumn
	 * @Description:判断收藏表字段中是否有空字段
	 * @param @return 设定文件
	 * @return boolean 返回类型
	 * @throws
	 */
	public boolean checkCollectionListNullColumn() {
		Cursor c = null;
		c = db.rawQuery("SELECT * FROM " + MY_FAVORITE_FORMY, null);
		try {
			if (c != null && c.getCount() > 0) {
				if (c.moveToNext()) {
					for (int i = 0; i < c.getColumnCount(); ++i) {
						if (c.isNull(i)) {
							String columnName = c.getColumnName(i);
							if (!TextUtils.isEmpty(columnName)) {
								if (columnName.equals("_namespell")) {
									continue;
								}
							}
							return true;
						}
					}
				}
			}

		} catch (Throwable t) {
			ALLog.d(t.toString());
		} finally {
			if (c != null) {
				try {
					c.close();
				} catch (Exception e) {
				}
			}
		}

		return false;
	}

	/**
	 * 检查礼物表是否有空的字段
	 * 
	 * @return
	 */
	public boolean checkGiftListNullColumn() {

		Cursor c = null;
		try {
			c = db.rawQuery("SELECT * FROM " + CUR_GIFT_LIST, null);
			if (c != null && c.getCount() > 0) {
				if (c.moveToNext()) {
					for (int i = 0; i < c.getColumnCount(); ++i) {
						if (c.isNull(i)) {
							String columnName = c.getColumnName(i);
							if (!TextUtils.isEmpty(columnName)) {
								// 礼物图片不再保存到数据库中
								if (columnName.equals("_imagePath")
										|| columnName.equals("_type")
										|| columnName.equals("_exchangecount")) {
									ALLog.d("我不管礼物图片保存路径");
									continue;
								}
							}
							ALLog.d("空的字段是 " + columnName);
							return true;
						}
					}
				}
			}

		} catch (Throwable t) {
			ALLog.d(t.toString());
		} finally {
			if (c != null) {
				try {
					c.close();
				} catch (Exception e) {
				}
			}
		}

		return false;
	}
}
